package com.ymttest.business.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.common.collect.Lists;
import com.shop2cn.iapi.delivery.parameter.DeliveryInfo;
import com.shop2cn.iapi.delivery.parameter.SqDeliveryReq;
import com.shop2cn.iapi.delivery.service.SqDeliveryCall;
import com.shop2cn.iapi.shenqisettlement.parameter.OnHpSettledReq;
import com.shop2cn.iapi.shenqisettlement.parameter.bean.AgentProductBean;
import com.shop2cn.iapi.shenqisettlement.service.DGSQBaseService;
import com.shop2cn.iapi.shenqisettlement.service.OnHpSettledCall;
import com.shop2cn.iapi.agentproducts.parameter.ProductDetailsBean;
import com.shop2cn.iapi.agentproducts.parameter.ProductDetailsDto;
import com.shop2cn.iapi.agentproducts.service.ProductDetailsCall;
import com.ymatou.iapi.dguser.parameter.UserCreateBean;
import com.ymatou.iapi.godmch.parameter.MchInfoVo;
import com.ymatou.iapi.godmch.parameter.SetPayModeBean;
import com.ymatou.iapi.godmch.parameter.createmchBean;
import com.ymatou.iapi.godmch.parameter.detailmchBean;
import com.ymatou.iapi.godmch.parameter.setShareTypeBean;
import com.ymatou.iapi.godmch.service.detailmchCall;
import com.ymatou.iapi.godmch.service.setShareTypeCall;
import com.ymatou.iapi.leaf.parameter.GetSeqReq;
import com.ymatou.iapi.leaf.service.GetSeqIdsCall;
import com.ymatou.iapi.optrade.parameter.enums.AppTerminalSourceEnum;
import com.ymatou.iapi.optrade.parameter.enums.CancelOrderTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.CouponApplianceTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.OrderSourceEnum;
import com.ymatou.iapi.optrade.parameter.enums.ProductRefundChannelEnum;
import com.ymatou.iapi.optrade.parameter.enums.PromotionTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.SalesTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.TerminalSourceEnum;
import com.ymatou.iapi.optrade.parameter.req.AddSellerMemoReq;
import com.ymatou.iapi.optrade.parameter.req.CancelOrderReq;
import com.ymatou.iapi.optrade.parameter.req.ChangeOrderDiscountReq;
import com.ymatou.iapi.optrade.parameter.req.ConfirmOfflinePayReq;
import com.ymatou.iapi.optrade.parameter.req.PayReq;
import com.ymatou.iapi.optrade.parameter.req.PlaceOrderReq;
import com.ymatou.iapi.optrade.parameter.req.ReduceSqProductStocksReq;
import com.ymatou.iapi.optrade.parameter.req.UpdateShenQiSellerMemoReq;
import com.ymatou.iapi.optrade.parameter.req.UpdateSqIdcardInfoReq;
import com.ymatou.iapi.optrade.parameter.utill.Utils;
import com.ymatou.iapi.optrade.parameter.vo.CatalogApportionVo;
import com.ymatou.iapi.optrade.parameter.vo.CouponVo;
import com.ymatou.iapi.optrade.parameter.vo.OrderGroupVo;
import com.ymatou.iapi.optrade.parameter.vo.OrderItemVo;
import com.ymatou.iapi.optrade.parameter.vo.OrderVo;
import com.ymatou.iapi.optrade.parameter.vo.SellerPromotionVo;
import com.ymatou.iapi.optrade.resp.Order;
import com.ymatou.iapi.optrade.resp.TradingServiceResp;
import com.ymatou.iapi.optrade.service.AddSellerMemoCall;
import com.ymatou.iapi.optrade.service.CancelOrderCall;
import com.ymatou.iapi.optrade.service.ChangeOrderDiscountCall;
import com.ymatou.iapi.optrade.service.ConfirmOfflinePayCall;
import com.ymatou.iapi.optrade.service.PayReqCall;
import com.ymatou.iapi.optrade.service.PlaceOrderCall;
import com.ymatou.iapi.optrade.service.ReduceSqProductStocksCall;
import com.ymatou.iapi.optrade.service.UpdateShenQiSellerMemoCall;
import com.ymatou.iapi.optrade.service.UpdateSqIdcardInfoCall;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.YMTTrading.TradingCallService;
import com.ymttest.business.service.shenqi.GodmchManageCallService;
import com.ymttest.database.model.shenqisettlement.CurrencyConfig;
import com.ymttest.database.sharding.db.sharding.model.OrderDetailPo;
import com.ymttest.database.sharding.db.sharding.model.OrderPo;
import com.ymttest.database.sharding.db.sharding.model.PaymentPo;
import com.ymttest.database.sharding.db.sharding.model.ShenqiProxyChainPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderShardingWapper;
import com.ymttest.database.sqlwapper.DGUserWapper;
import com.ymttest.database.sqlwapper.shenqisettlement.CurrencyConfigWrapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;

public class TradingForDGSQCallService {

	private static long autotest_goodsOwnerId = Long.valueOf(EnvSetup
			.getData("autotest_goodsOwnerId"));
	private static String autotest_goodsOwnerName = String.valueOf(EnvSetup
			.getData("autotest_goodsOwnerName"));
	
	private static OnHpSettledReq hpSettledReq = new OnHpSettledReq();
	private static OnHpSettledCall hpSettledCall = new OnHpSettledCall();

	/**
	 * buildDGSQStandPlaceOrderReq 一个商家，一个商品，生成一个订单
	 * 
	 * @param salesman
	 *            店主的销售员
	 * @param discount
	 *            代下单时调价.大于0，加价；小于0；减价
	 * @userId userId 买家id
	 * @sellerId sellerId 买手id
	 * @sellerId sellerName 买手名称
	 * @return
	 */
	public static PlaceOrderReq buildDGSQStandPlaceOrderReq(long salesman,
			BigDecimal discount, long userId, AgentProductBean productBean,
			long goodOwnerId, boolean useCoupon, boolean supportOfflinePay) {

		PlaceOrderReq req = new PlaceOrderReq();
		req.setAddressId(772208L);
		req.setRecvMobile("136" + TestDataManager.getRandomNum(8));
		req.setRecvName("testUser");
		req.setAppId("ymt autotest");
		req.setUserId(userId);

		req.setFromShenqi(true);
		req.setSalesman(salesman);
		req.setDiscount(discount);

		req.setAddress("上海 静安 江场三路");
		req.setPostCode("200000");

		req.setEquipmentId(TestDataManager.getRandomUUID().toString());
		req.setDeviceId(TestDataManager.getRandomUUID().toString());
		req.setSourceIp(TestDataManager.getRandomIp());

		req.setAppTerminalSource(AppTerminalSourceEnum.Phone);
		req.setOrderSource(OrderSourceEnum.Wechat);
		req.setTerminalSource(TerminalSourceEnum.Android);

		req.setMainOrderId(genMainOrderId(req.getUserId()));
		
		req.setSupportOfflinePay(supportOfflinePay);

		OrderVo orderVo;

		orderVo = createOrderVo(Lists.newArrayList(productBean));

		orderVo.setGoodsOwnerId(goodOwnerId);
		orderVo.setShenqiLogisticsType(999);
		orderVo.setShenqiIdCardRequirement(2);

		// 一个商家一个订单一个商品
		OrderGroupVo groupVo1 = new OrderGroupVo();

		groupVo1.setSellerId(productBean.getSellerId());
		groupVo1.setSellerLoginId(productBean.getSellerLoginId());

		groupVo1.setSellerCoupon(null);

		groupVo1.setOrders(Lists.newArrayList(orderVo));

		req.setOrderGroups(Lists.newArrayList(groupVo1));

		req.setCurrencySymbol("$");
		req.setPayChannelType(1);
		
		if (useCoupon) {
			
			long sellerId = groupVo1.getSellerId();
			
			// 商家券
			CouponVo sellerCoupon1 = TradingForDGSQCallService.createSellerCouponVo(
					userId, sellerId, new BigDecimal(30), BigDecimal.TEN);

			groupVo1.setSellerCoupon(sellerCoupon1);
		}
		
		return req;
	}
	
	public static PlaceOrderReq buildDGSQStandPlaceOrderReq(long salesman,
			BigDecimal discount, long userId, AgentProductBean productBean,
			long goodOwnerId, boolean useCoupon) {

		return buildDGSQStandPlaceOrderReq(salesman, discount, userId,
				productBean, goodOwnerId, useCoupon, false);
	}
	
	/**
	 * buildDGSQStandPlaceOrderReq 一个商家，一个商品，生成一个订单
	 * 
	 * @param salesman
	 *            店主的销售员
	 * @param discount
	 *            代下单时调价.大于0，加价；小于0；减价
	 * @userId userId 买家id
	 * @sellerId sellerId 买手id
	 * @sellerId sellerName 买手名称
	 * @return
	 */
	public static PlaceOrderReq buildDGSQStandPlaceOrderReq(long salesman,
			BigDecimal discount, long userId, AgentProductBean productBean,
			long goodOwnerId) {

		return buildDGSQStandPlaceOrderReq(salesman, discount, userId,
				productBean, goodOwnerId, false, false);
	}

	/**
	 * createOrderGroupVo
	 * 
	 * @param sellerId
	 * @param sellerName
	 * @param goodOwnerId
	 * @return OrderGroupVo
	 */
	public static OrderGroupVo createOrderGroupVo(AgentProductBean productBean,
			long goodOwnerId) {

		OrderGroupVo groupVo = new OrderGroupVo();

		groupVo.setSellerId(productBean.getSellerId());
		groupVo.setSellerLoginId(productBean.getSellerLoginId());
		groupVo.setSellerCoupon(null);

		OrderVo orderVo = createOrderVo(Lists.newArrayList(productBean));

		orderVo.setGoodsOwnerId(goodOwnerId);
		orderVo.setShenqiLogisticsType(100);
		orderVo.setShenqiIdCardRequirement(0);

		groupVo.setOrders(Lists.newArrayList(orderVo));

		return groupVo;
	}

	/**
	 * createOrderVo
	 * 
	 * @param productIds
	 * @return OrderVo
	 */
	public static OrderVo createOrderVo(List<AgentProductBean> agentProductBeanList) {

		OrderVo order = new OrderVo();

		order.setLogisticsType(LogisticsTypeEnum.Unknown);
		order.setAutoCancelOrderHours(BigDecimal.ONE);
		order.setLeaveWord("尽快发货！");

		List<OrderItemVo> items = new ArrayList<OrderItemVo>();

		for (AgentProductBean product : agentProductBeanList) {
			items.add(createOrderItemVo(product.getProductId(), product
					.getCatalogList().get(0)));
		}

		order.setOrderItems(items);
		
		order.setGoodsOwnerId(agentProductBeanList.get(0).getGoodsOwnerId());
		order.setShenqiLogisticsType(999);
		order.setShenqiIdCardRequirement(2);
		
		return order;
	}

	/**
	 * createOrderItemVo
	 * 
	 * @param productId
	 * @return OrderItemVo
	 */
	public static OrderItemVo createOrderItemVo(String productId,
			String catalogId) {

		OrderItemVo orderItem = new OrderItemVo();

		// BigDecimal price = new BigDecimal(new Random().nextInt(50) + 30);
		BigDecimal price = new BigDecimal(new Random().nextInt(50) + 1301);
//		BigDecimal price = new BigDecimal(new Random().nextInt(50) + 10542);
		BigDecimal freight = new BigDecimal(new Random().nextInt(20) + 10);

		orderItem.setProductPrice(price.subtract(BigDecimal.TEN));
		orderItem.setOriginalPrice(price);

		orderItem.setFreight(freight);
		orderItem.setProductNum(new Random().nextInt(4) + 2);
//		orderItem.setProductNum(1);
		orderItem.setProductId(productId);
		orderItem.setCatalogId(catalogId);
		orderItem.setSalesType(SalesTypeEnum.AlreadyInStock);
		orderItem.setFirstCategoryId(1001);
		orderItem.setSecondCategoryId(1002);
		orderItem.setThirdCategoryId(1003);
		orderItem.setPreSale(false);
		orderItem.setProductRefundChannel(ProductRefundChannelEnum.None);
		orderItem
				.setPictureUrl("http://pic1.ymatou.com/G01/shangou/M00/39/85/rBBlD1k-U5eAMqEfAAIULSyYXWM521_104_78_n_w_o.jpg");
		orderItem.setSku("sku111");
		orderItem.setProperty("属性");
		orderItem.setBrandId(1234);
		orderItem.setProductName("自动化测试商品+" + TestDataManager.getRandomNum(10));
		orderItem.setProductRecordNo("9876");

		return orderItem;
	}

	/**
	 * 根據catalogId 获取关系链
	 * 
	 * @param catalogId
	 * @return
	 */
	public static List<ShenqiProxyChainPo> getProxyChainInfo(String catalogId) {

		List<ShenqiProxyChainPo> shenqiProxyChainPoList = new ArrayList<ShenqiProxyChainPo>();

		YmatouEasyCall queryAgentPriceChainCall = new YmatouEasyCall("",
				"POST", "JSON");
		String orderJson = "{\"catalogIds\":[\"" + catalogId + "\"]}";
		queryAgentPriceChainCall
				.setUrl("http://agentproducts.iapi.ymatou.com/product/queryAgentPriceChain");
		queryAgentPriceChainCall.setData(orderJson);

		try {
			queryAgentPriceChainCall.callService();

			JSONObject data = new JSONObject(
					queryAgentPriceChainCall.getReturnData())
					.optJSONObject("data");

			if (null == data)
				return null;
			else {

				Logger.debug("returndata:"
						+ data.optJSONObject("catalogPriceLinkMap")
								.optJSONArray(catalogId));
				JSONArray proxyChain = data
						.optJSONObject("catalogPriceLinkMap").optJSONArray(
								catalogId);

				for (int i = 0; i < proxyChain.length(); i++) {

					JSONObject object = new JSONObject(proxyChain.get(i)
							.toString());
					ShenqiProxyChainPo po = new ShenqiProxyChainPo();

					po.setTitle(object.optString("title"));
					po.setPictureUrl(object.optString("pictureUrl"));
					po.setFromParentPrice(new BigDecimal(object
							.optDouble("fromParentPrice")).setScale(2));
					po.setToChildPrice(new BigDecimal(object
							.optDouble("toChildPrice")).setScale(2));
					po.setIndexInChain(i);
					po.setSellerId(object.optLong("sellerId"));
					po.setCatalogId(catalogId);
					po.setProxyCatalogId(object.optString("catalogId"));

					if (i == proxyChain.length() - 1) {
						po.setChildSellerId(0L);
					} else {
						po.setChildSellerId(new JSONObject(proxyChain
								.get(i + 1).toString()).optLong("sellerId"));
					}

					String currency = data.getString("currency");
					po.setCurrency(currency);
					
					shenqiProxyChainPoList.add(po);
				}
			}

			Logger.debug("ShenqiProxyChainPoList:" + shenqiProxyChainPoList);

		} catch (Exception e) {

			e.printStackTrace();
		}

		return shenqiProxyChainPoList;
	}
	
	/**
	 * 根據catalogId 获取关系链
	 * 
	 * @param catalogId
	 * @return
	 */
	public static List<ShenqiProxyChainPo> getInheritedProxyChainInfo(String catalogId, long sellerId) {

		List<ShenqiProxyChainPo> shenqiProxyChainPoList = new ArrayList<ShenqiProxyChainPo>();

		YmatouEasyCall queryAgentPriceChainCall = new YmatouEasyCall("",
				"POST", "JSON");
		String orderJson = "{\"catalogIds\":[\"" + catalogId + "\"], \"userId\":" + sellerId + "}";
		queryAgentPriceChainCall
				.setUrl("http://agentproducts.iapi.ymatou.com/product/queryAgentPriceChain");
		queryAgentPriceChainCall.setData(orderJson);

		try {
			queryAgentPriceChainCall.callService();

			JSONObject data = new JSONObject(
					queryAgentPriceChainCall.getReturnData())
					.optJSONObject("data");

			if (null == data)
				return null;
			else {

				Logger.debug("returndata:"
						+ data.optJSONObject("catalogPriceLinkMap")
								.optJSONArray(catalogId));
				JSONArray proxyChain = data
						.optJSONObject("catalogPriceLinkMap").optJSONArray(
								catalogId);

				for (int i = 0; i < proxyChain.length(); i++) {

					JSONObject object = new JSONObject(proxyChain.get(i)
							.toString());
					ShenqiProxyChainPo po = new ShenqiProxyChainPo();

					po.setTitle(object.optString("title"));
					po.setPictureUrl(object.optString("pictureUrl"));
					po.setFromParentPrice(new BigDecimal(object
							.optDouble("fromParentPrice")).setScale(2));
					po.setToChildPrice(new BigDecimal(object
							.optDouble("toChildPrice")).setScale(2));
					po.setIndexInChain(i);
					po.setSellerId(object.optLong("sellerId"));
					po.setCatalogId(catalogId);
					po.setProxyCatalogId(object.optString("catalogId"));

					if (i == proxyChain.length() - 1) {
						po.setChildSellerId(0L);
					} else {
						po.setChildSellerId(new JSONObject(proxyChain
								.get(i + 1).toString()).optLong("sellerId"));
					}
					
					String currency = data.getString("currency");
					po.setCurrency(currency);

					shenqiProxyChainPoList.add(po);
				}
			}

			Logger.debug("ShenqiProxyChainPoList:" + shenqiProxyChainPoList);

		} catch (Exception e) {

			e.printStackTrace();
		}

		return shenqiProxyChainPoList;
	}

	/**
	 * 根據catalogId, sellerid 获取sellerid对应的规格价格
	 * 
	 * @param catalogId
	 * @param sellerId
	 * @return
	 */
	public static ShenqiProxyChainPo getProxyChainInfo(String catalogId,
			long sellerId) {

		ShenqiProxyChainPo po = new ShenqiProxyChainPo();

		YmatouEasyCall queryAgentPriceChainCall = new YmatouEasyCall("",
				"POST", "JSON");
		String orderJson = "{\"catalogIds\":[\"" + catalogId + "\"], \"userId\":" + sellerId + "}";
		queryAgentPriceChainCall
				.setUrl("http://agentproducts.iapi.ymatou.com/product/queryAgentPriceChain");
		queryAgentPriceChainCall.setData(orderJson);

		try {
			queryAgentPriceChainCall.callService();

			JSONObject data = new JSONObject(
					queryAgentPriceChainCall.getReturnData())
					.optJSONObject("data");

			if (null == data)
				return null;
			else {

				Logger.debug("returndata:"
						+ data.optJSONObject("catalogPriceLinkMap")
								.optJSONArray(catalogId));
				JSONArray proxyChain = data
						.optJSONObject("catalogPriceLinkMap").optJSONArray(
								catalogId);

				for (int i = 0; i < proxyChain.length(); i++) {

					JSONObject object = new JSONObject(proxyChain.get(i)
							.toString());

					if (object.optLong("sellerId") == sellerId) {

						po = new ShenqiProxyChainPo();

						po.setTitle(object.optString("title"));
						po.setPictureUrl(object.optString("pictureUrl"));
						po.setFromParentPrice(new BigDecimal(object
								.optDouble("fromParentPrice")).setScale(2));
						po.setToChildPrice(new BigDecimal(object
								.optDouble("toChildPrice")).setScale(2));
						po.setIndexInChain(i);
						po.setSellerId(object.optLong("sellerId"));
						po.setCatalogId(catalogId);

						if (i == proxyChain.length() - 1) {
							po.setChildSellerId(0L);
						} else {
							po.setChildSellerId(new JSONObject(proxyChain.get(
									i + 1).toString()).optLong("sellerId"));
						}
					}
				}
				
				String currency = data.getString("currency");
				po.setCurrency(currency);
			}

			Logger.debug("shenqiProxyChainPo:" + po);

		} catch (Exception e) {

			e.printStackTrace();
		}

		return po;
	}
	
	public static AgentProductBean createGoodsOwnerProduct(Long goodsOwnerId,
			String currency, Boolean isForeignCurrency) throws Exception {

		String productId = "";

		if (!isForeignCurrency) {
			currency = "CNY";
			productId = DGSQBaseService.createAgentProduct(
					goodsOwnerId.intValue(), autotest_goodsOwnerName, true,
					currency);
		} else {

			currency = getMchInfoBySellerId((long) goodsOwnerId).getCurrency();
			productId = DGSQBaseService.createAgentProduct(
					goodsOwnerId.intValue(), autotest_goodsOwnerName, true,
					currency);
		}

		AgentProductBean agentProductBean = new AgentProductBean();

		agentProductBean.setProductId(productId);
		agentProductBean.setCatalogList(DGSQBaseService
				.getCatalogIdList(productId));
		agentProductBean.setSellerId(goodsOwnerId);
		agentProductBean.setCurrency(currency);
		agentProductBean.setSellerLoginId("autotest");

		return agentProductBean;
	}
	
	/**
	 * 创建供货商商品
	 * @param country
	 * @param currency
	 * @param isForeignCurrency
	 * @return
	 * @throws Exception
	 */
	public static AgentProductBean createSupplierProduct(String country,
			String currency, Boolean isForeignCurrency) throws Exception {

		String productId = "";
		
		Integer supplierId =  DGSQBaseService.createApplySupplier(country);

		if (!isForeignCurrency) {
			currency = "CNY";
			productId = DGSQBaseService.createAgentProduct(
					supplierId.intValue(), "", false,
					currency);
		} else {

			currency = getMchInfoBySellerId((long) supplierId).getCurrency();
			productId = DGSQBaseService.createAgentProduct(
					supplierId.intValue(), "", false,
					currency);
		}

		AgentProductBean agentProductBean = new AgentProductBean();

		agentProductBean.setProductId(productId);
		agentProductBean.setCatalogList(DGSQBaseService
				.getCatalogIdList(productId));
		agentProductBean.setSellerId(supplierId);
		agentProductBean.setCurrency(currency);
		agentProductBean.setSellerLoginId("autotest");
		agentProductBean.setGoodsOwnerId((long)supplierId);

		return agentProductBean;
	}

	/**
	 * 创建代理链并将商品import给各个代理商
	 * 
	 * @param goodsOwnerId
	 *            货头Id
	 * @param n
	 *            n个中间商
	 * @param needAgent
	 *            是否再添加一个代理
	 * @return AgentProductBean
	 * @throws Exception
	 */
	public static AgentProductBean createProxychain(int goodsOwnerId, int n,
			boolean needAgent) throws Exception {

		return createProxychain(goodsOwnerId, n, needAgent, false);
	}

	/**
	 * 创建代理链并将商品import给各个代理商(指定币种)
	 * 
	 * @param goodsOwnerId
	 *            货头Id
	 * @param n
	 *            n个中间商
	 * @param needAgent
	 *            是否再添加一个代理
	 * @param currency
	 *            指定币种（mch_info表multiCurrency支持的币种）
	 * @return AgentProductBean
	 * @throws Exception
	 */
	public static AgentProductBean createProxychain(int goodsOwnerId, int n,
			boolean needAgent, String currency) throws Exception {

		AgentProductBean agentProductBean = null;
		int parentUserId = goodsOwnerId;
		String productId = "";

		if (currency.equalsIgnoreCase("KRW"))
			currency = "USD";
		
		productId = DGSQBaseService.createAgentProduct(goodsOwnerId,
				autotest_goodsOwnerName, true, currency);
		
		if (n == 0) {
			
			agentProductBean = new AgentProductBean();
			
			agentProductBean.setSellerId(parentUserId);
			agentProductBean.setSellerLoginId(new DGUserWapper().selectDGUserInfo(
					parentUserId).get(0).getLoginId());
			agentProductBean.setProductId(productId);
			agentProductBean.setRootProductId(productId);
			agentProductBean.setCatalogList(DGSQBaseService.getCatalogIdList(productId));
			agentProductBean.setRootCatalogList(DGSQBaseService.getCatalogIdList(productId));
		}

		for (int i = 0; i < n; i++) {

			// 创建一个新的渠道商并绑定上级
			createmchBean createmchBean = DGSQBaseService
					.bindChannel(parentUserId);

			agentProductBean = DGSQBaseService
					.importAgentProduct(createmchBean.getMchId(), "",
							productId, parentUserId, true);

			if (needAgent && i == n - 1) {

				createmchBean bean = DGSQBaseService.createAgent(
						createmchBean.getMchId(), "CHN");

				AgentProductBean agentProduct = DGSQBaseService
						.importAgentProduct(bean.getMchId(), "",
								agentProductBean.getProductId(),
								createmchBean.getMchId(), false);

				agentProduct.setSellerId(bean.getMchId());
				agentProduct.setSellerLoginId(new DGUserWapper()
						.selectDGUserInfo(bean.getMchId()).get(0).getLoginId());
				agentProduct.setCurrency(currency);

				return agentProduct;
			}

			parentUserId = createmchBean.getMchId();
			productId = agentProductBean.getProductId();
			agentProductBean.setSellerId(parentUserId);
			agentProductBean.setSellerLoginId(new DGUserWapper()
					.selectDGUserInfo(createmchBean.getMchId()).get(0)
					.getLoginId());
		}

		agentProductBean.setCurrency(currency);
		agentProductBean.setGoodsOwnerId((long)goodsOwnerId);

		return agentProductBean;
	}
	
	/**
	 * 创建代理链并将商品import给各个代理商
	 * 
	 * @param goodsOwnerId
	 *            货头Id
	 * @param n
	 *            n个中间商
	 * @param needAgent
	 *            是否再添加一个代理
	 * @param isForeignCurrency
	 *            是否使用外币
	 * @return AgentProductBean
	 * @throws Exception
	 */
	public static AgentProductBean createProxychain(int goodsOwnerId, int n,
			boolean needAgent, boolean isForeignCurrency) throws Exception {

		AgentProductBean agentProductBean = null;
		int parentUserId = goodsOwnerId;
		String productId = "";
		String currency = "";

		if (!isForeignCurrency) {
			currency = "CNY";
			productId = DGSQBaseService.createAgentProduct(goodsOwnerId,
					autotest_goodsOwnerName, true, currency);
		} else {
			
			currency = getMchInfoBySellerId((long)goodsOwnerId).getCurrency();
			
			if (currency.equalsIgnoreCase("KRW"))
				currency = "USD";
			
			productId = DGSQBaseService.createAgentProduct(goodsOwnerId,
					autotest_goodsOwnerName, true, currency);
		}
		
		if (n == 0) {
			
			agentProductBean = new AgentProductBean();
			
			agentProductBean.setSellerId(parentUserId);
			agentProductBean.setSellerLoginId(new DGUserWapper().selectDGUserInfo(
					parentUserId).get(0).getLoginId());
			agentProductBean.setProductId(productId);
			agentProductBean.setRootProductId(productId);
			agentProductBean.setCatalogList(DGSQBaseService.getCatalogIdList(productId));
			agentProductBean.setRootCatalogList(DGSQBaseService.getCatalogIdList(productId));
		}

		for (int i = 0; i < n; i++) {

			// 创建一个新的渠道商并绑定上级
			createmchBean createmchBean = DGSQBaseService
					.bindChannel(parentUserId);

			agentProductBean = DGSQBaseService
					.importAgentProduct(createmchBean.getMchId(), "",
							productId, parentUserId, true);

			if (needAgent && i == n - 1) {

				createmchBean bean = DGSQBaseService.createAgent(
						createmchBean.getMchId(), "CHN");

				AgentProductBean agentProduct = DGSQBaseService
						.importAgentProduct(bean.getMchId(), "",
								agentProductBean.getProductId(),
								createmchBean.getMchId(), false);

				agentProduct.setSellerId(bean.getMchId());
				agentProduct.setSellerLoginId(new DGUserWapper()
						.selectDGUserInfo(bean.getMchId()).get(0).getLoginId());
				agentProduct.setCurrency(currency);

				return agentProduct;
			}

			parentUserId = createmchBean.getMchId();
			productId = agentProductBean.getProductId();
			agentProductBean.setSellerId(parentUserId);
			agentProductBean.setSellerLoginId(new DGUserWapper()
					.selectDGUserInfo(createmchBean.getMchId()).get(0)
					.getLoginId());
		}

		agentProductBean.setCurrency(currency);
		agentProductBean.setGoodsOwnerId((long)goodsOwnerId);

		return agentProductBean;
	}
	
	/**
	 * 创建继承代理链并将商品import给各个代理商
	 * 
	 * @param goodsOwnerId
	 *            货头Id
	 * @param isForeignCurrency
	 *            是否使用外币
	 * @return AgentProductBean
	 * @throws Exception
	 */
	public static AgentProductBean createInheritedProxychain(int goodsOwnerId,
			boolean isForeignCurrency) throws Exception {

		String productId = "";
		String currency = "";

		if (!isForeignCurrency) {
			currency = "CNY";
		} else {
			currency = getMchInfoBySellerId((long)goodsOwnerId).getCurrency();
		}
		
		productId = DGSQBaseService.createAgentProduct(goodsOwnerId,
				autotest_goodsOwnerName, true, currency);
		
		createmchBean bean = DGSQBaseService.createInheritedAgent(goodsOwnerId);
		
		AgentProductBean agentProductBean = new AgentProductBean();
		
		agentProductBean.setProductId(productId);
		agentProductBean.setCatalogList(DGSQBaseService.getCatalogIdList(productId));
		agentProductBean.setSellerId(bean.getMchId());
		agentProductBean.setSellerLoginId(new DGUserWapper()
				.selectDGUserInfo(bean.getMchId()).get(0).getLoginId());
		agentProductBean.setCurrency(currency);

		return agentProductBean;
	}
	
	/**
	 * 创建独立商家代理链并将商品import给各个代理商
	 * 
	 * @param goodsOwnerId
	 *            货头Id
	 * @param isForeignCurrency
	 *            是否使用外币
	 * @return AgentProductBean
	 * @throws Exception
	 */
	public static AgentProductBean createIndependenceProxychain(int goodsOwnerId,
			boolean isForeignCurrency) throws Exception {

		TradingForDGSQCallService.setPayModeBean(goodsOwnerId);
		
		String productId = "";
		String currency = "";

		if (!isForeignCurrency) {
			currency = "CNY";
		} else {
			currency = getMchInfoBySellerId((long)goodsOwnerId).getCurrency();
		}
		
		createmchBean bean = DGSQBaseService.createAgent(
				goodsOwnerId, "CHN");
		
		productId = DGSQBaseService.createAgentProduct(goodsOwnerId,
				autotest_goodsOwnerName, true, currency);

		AgentProductBean agentProduct = DGSQBaseService
				.importAgentProduct(bean.getMchId(), "",
						productId,
						goodsOwnerId, false);

		agentProduct.setSellerId(bean.getMchId());
		agentProduct.setSellerLoginId(new DGUserWapper()
				.selectDGUserInfo(bean.getMchId()).get(0).getLoginId());
		agentProduct.setCurrency(currency);
		
//		productId = DGSQBaseService.createAgentProduct(goodsOwnerId,
//				autotest_goodsOwnerName, true, currency);
//		
//		applyAgentBean bean = DGSQBaseService.createIndependenceAgent(goodsOwnerId, "JPN");
//		
//		AgentProductBean agentProductBean = DGSQBaseService
//				.importAgentProduct(bean.getMchId(), "",
//						productId, goodsOwnerId, true);
//		
////		AgentProductBean agentProductBean = new AgentProductBean();
//		
//		agentProductBean.setProductId(productId);
//		agentProductBean.setCatalogList(DGSQBaseService.getCatalogIdList(productId));
//		agentProductBean.setSellerId(goodsOwnerId);
//		agentProductBean.setSellerLoginId(new DGUserWapper()
//				.selectDGUserInfo(goodsOwnerId).get(0).getLoginId());
//		agentProductBean.setCurrency(currency);

		return agentProduct;
	}

	/**
	 * 创建UK代理链并将商品import给各个代理商
	 * 
	 * @param goodsOwnerId
	 *            货头Id
	 * @param n
	 *            n个中间商
	 * @param needAgent
	 *            是否再添加一个代理
	 * @return AgentProductBean
	 * @throws Exception
	 */
	public static AgentProductBean createUKProxychain(int goodsOwnerId, int n,
			boolean needAgent) throws Exception {

		return createUKProxychain(goodsOwnerId, n, needAgent, false);
	}

	/**
	 * 创建代理链并将商品import给各个代理商
	 * 
	 * @param goodsOwnerId
	 *            货头Id
	 * @param n
	 *            n个中间商
	 * @param needAgent
	 *            是否再添加一个代理
	 * @param isForeignCurrency
	 *            是否使用外币支付
	 * 
	 * @return
	 * @throws Exception
	 */
	public static AgentProductBean createUKProxychain(int goodsOwnerId, int n,
			boolean needAgent, boolean isForeignCurrency) throws Exception {

		AgentProductBean agentProductBean = null;
		int parentUserId = goodsOwnerId;
		String productId = "";
		String currency = "";

		if (!isForeignCurrency) {
			currency = "CNY";
			productId = DGSQBaseService.createAgentProduct(parentUserId, "",
					true, "CNY");
		} else {
			currency = getMchInfoBySellerId((long)goodsOwnerId).getCurrency();
			productId = DGSQBaseService.createAgentProduct(parentUserId, "",
					true, currency);
		}

		for (int i = 0; i < n; i++) {

			// 创建一个新的渠道商并绑定上级
			createmchBean createmchBean = DGSQBaseService.bindChannel(
					parentUserId, "GBR", null);

			agentProductBean = DGSQBaseService
					.importAgentProduct(createmchBean.getMchId(), "",
							productId, parentUserId, true);

			if (needAgent && i == n - 1) {

				createmchBean bean = DGSQBaseService.createAgent(
						createmchBean.getMchId(), "CHN");

				AgentProductBean agentProduct = DGSQBaseService
						.importAgentProduct(bean.getMchId(), "",
								agentProductBean.getProductId(),
								createmchBean.getMchId(), false);

				agentProduct.setSellerId(bean.getMchId());
				agentProduct.setSellerLoginId(new DGUserWapper()
						.selectDGUserInfo(bean.getMchId()).get(0).getLoginId());
				agentProduct.setCurrency(currency);

				return agentProduct;
			}

			parentUserId = createmchBean.getMchId();
			productId = agentProductBean.getProductId();
			agentProductBean.setSellerId(parentUserId);
			agentProductBean.setSellerLoginId(new DGUserWapper()
					.selectDGUserInfo(createmchBean.getMchId()).get(0)
					.getLoginId());
		}

		agentProductBean.setCurrency(currency);

		return agentProductBean;
	}

	/**
	 * 创建代理链并将商品import给各个代理商
	 * 
	 * @param goodsOwnerId
	 *            货头Id
	 * @param n
	 *            n个中间商
	 * @param needAgent
	 *            是否再添加一个代理
	 * @return AgentProductBean
	 * @throws Exception
	 */
	public static AgentProductBean createJPProxychain(int goodsOwnerId, int n,
			boolean needAgent) throws Exception {

		return createJPProxychain(goodsOwnerId, n, needAgent, false);
	}

	/**
	 * 创建代理链并将商品import给各个代理商
	 * 
	 * @param goodsOwnerId 500058147
	 *            货头Id
	 * @param n
	 *            n个中间商
	 * @param needAgent
	 *            是否再添加一个代理
	 * @param isForeignCurrency
	 *            是否使用外币支付
	 * 
	 * @return
	 * @throws Exception
	 */
	public static AgentProductBean createJPProxychain(int goodsOwnerId, int n,
			boolean needAgent, boolean isForeignCurrency) throws Exception {

		AgentProductBean agentProductBean = null;
		int parentUserId = goodsOwnerId;
		String productId = "";
		String currency = "";

		if (!isForeignCurrency) {
			currency = "CNY";
			productId = DGSQBaseService.createAgentProduct(parentUserId, "",
					true, "CNY");
		} else {
			currency = getMchInfoBySellerId((long)goodsOwnerId).getCurrency();
			productId = DGSQBaseService.createAgentProduct(parentUserId, "",
					true, currency);
		}

		for (int i = 0; i < n; i++) {

			// 创建一个新的渠道商并绑定上级
			createmchBean createmchBean = DGSQBaseService.bindChannel(
					parentUserId, "JPN", null);

			agentProductBean = DGSQBaseService
					.importAgentProduct(createmchBean.getMchId(), "",
							productId, parentUserId, true);

			if (needAgent && i == n - 1) {

				createmchBean bean = DGSQBaseService.createAgent(
						createmchBean.getMchId(), "CHN");

				AgentProductBean agentProduct = DGSQBaseService
						.importAgentProduct(bean.getMchId(), "",
								agentProductBean.getProductId(),
								createmchBean.getMchId(), false);

				agentProduct.setSellerId(bean.getMchId());
				agentProduct.setSellerLoginId(new DGUserWapper()
						.selectDGUserInfo(bean.getMchId()).get(0).getLoginId());
				agentProduct.setCurrency(currency);

				return agentProduct;
			}

			parentUserId = createmchBean.getMchId();
			productId = agentProductBean.getProductId();
			agentProductBean.setSellerId(parentUserId);
			agentProductBean.setSellerLoginId(new DGUserWapper()
					.selectDGUserInfo(createmchBean.getMchId()).get(0)
					.getLoginId());
		}

		agentProductBean.setCurrency(currency);

		return agentProductBean;
	}
	
	/**
	 * 创建代理链并将商品import给各个代理商
	 * 韩币不支持本国货币，所以还是使用CNY
	 * @param goodsOwnerId
	 *            货头Id
	 * @param n
	 *            n个中间商
	 * @param needAgent
	 *            是否再添加一个代理
	 * @param isForeignCurrency
	 *            是否使用外币支付
	 * 
	 * @return
	 * @throws Exception
	 */
	public static AgentProductBean createKRProxychain(int goodsOwnerId, int n,
			boolean needAgent) throws Exception {

		AgentProductBean agentProductBean = null;
		int parentUserId = goodsOwnerId;
		String productId = "";
		String currency = "CNY";
		
		productId = DGSQBaseService.createAgentProduct(parentUserId, "",
				true, currency);

		for (int i = 0; i < n; i++) {

			// 创建一个新的渠道商并绑定上级
			createmchBean createmchBean = DGSQBaseService.bindChannel(
					parentUserId, "KOR", null);

			agentProductBean = DGSQBaseService
					.importAgentProduct(createmchBean.getMchId(), "",
							productId, parentUserId, true);

			if (needAgent && i == n - 1) {

				createmchBean bean = DGSQBaseService.createAgent(
						createmchBean.getMchId(), "CHN");

				AgentProductBean agentProduct = DGSQBaseService
						.importAgentProduct(bean.getMchId(), "",
								agentProductBean.getProductId(),
								createmchBean.getMchId(), false);

				agentProduct.setSellerId(bean.getMchId());
				agentProduct.setSellerLoginId(new DGUserWapper()
						.selectDGUserInfo(bean.getMchId()).get(0).getLoginId());
				agentProduct.setCurrency(currency);

				return agentProduct;
			}

			parentUserId = createmchBean.getMchId();
			productId = agentProductBean.getProductId();
			agentProductBean.setSellerId(parentUserId);
			agentProductBean.setSellerLoginId(new DGUserWapper()
					.selectDGUserInfo(createmchBean.getMchId()).get(0)
					.getLoginId());
		}

		agentProductBean.setCurrency(currency);

		return agentProductBean;
	}
	
	/**
	 * 创建新西兰代理链并将商品import给各个代理商
	 * 新西兰不支持本国货币
	 * @param goodsOwnerId
	 *            货头Id
	 * @param n
	 *            n个中间商
	 * @param needAgent
	 *            是否再添加一个代理
	 * @param isForeignCurrency
	 *            是否使用外币支付
	 * 
	 * @return
	 * @throws Exception
	 */
	public static AgentProductBean createNZLProxychain(int goodsOwnerId, int n,
			boolean needAgent) throws Exception {

		AgentProductBean agentProductBean = null;
		int parentUserId = goodsOwnerId;
		String productId = "";
		String currency = "CNY";
		
		productId = DGSQBaseService.createAgentProduct(parentUserId, "",
				true, currency);
		
		if (n == 0) {
			
			agentProductBean = new AgentProductBean();
			
			agentProductBean.setSellerId(parentUserId);
			agentProductBean.setSellerLoginId(new DGUserWapper()
					.selectDGUserInfo(parentUserId).get(0).getLoginId());
			agentProductBean.setProductId(productId);
			agentProductBean.setRootProductId(productId);
			agentProductBean.setCatalogList(DGSQBaseService.getCatalogIdList(productId));
			agentProductBean.setRootCatalogList(DGSQBaseService.getCatalogIdList(productId));
		}

		for (int i = 0; i < n; i++) {

			// 创建一个新的渠道商并绑定上级
			createmchBean createmchBean = DGSQBaseService.bindChannel(
					parentUserId, "NZL", null);

			agentProductBean = DGSQBaseService
					.importAgentProduct(createmchBean.getMchId(), "",
							productId, parentUserId, true);

			if (needAgent && i == n - 1) {

				createmchBean bean = DGSQBaseService.createAgent(
						createmchBean.getMchId(), "CHN");

				AgentProductBean agentProduct = DGSQBaseService
						.importAgentProduct(bean.getMchId(), "",
								agentProductBean.getProductId(),
								createmchBean.getMchId(), false);

				agentProduct.setSellerId(bean.getMchId());
				agentProduct.setSellerLoginId(new DGUserWapper()
						.selectDGUserInfo(bean.getMchId()).get(0).getLoginId());
				agentProduct.setCurrency(currency);

				return agentProduct;
			}

			parentUserId = createmchBean.getMchId();
			productId = agentProductBean.getProductId();
			agentProductBean.setSellerId(parentUserId);
			agentProductBean.setSellerLoginId(new DGUserWapper()
					.selectDGUserInfo(createmchBean.getMchId()).get(0)
					.getLoginId());
		}

		agentProductBean.setCurrency(currency);

		return agentProductBean;
	}
	
	/**
	 * 创建渠道商
	 * @param parentUserId
	 * @param productId
	 * @param country
	 * @return
	 * @throws Exception
	 */
	public static AgentProductBean createChannel(long parentUserId,
			String productId, String country) throws Exception {

		AgentProductBean agentProductBean = null;

		// 创建一个新的渠道商并绑定上级
		createmchBean createmchBean = DGSQBaseService.bindChannel((int)parentUserId,
				country, null);
		String currency = getMchInfoBySellerId((long) createmchBean.getMchId())
				.getCurrency();
		
//		productId = DGSQBaseService.createAgentProduct(parentUserId,
//				autotest_goodsOwnerName, true, currency);

		agentProductBean = DGSQBaseService.importAgentProduct(
				createmchBean.getMchId(), "", productId, (int)parentUserId, true);

		parentUserId = createmchBean.getMchId();
		productId = agentProductBean.getProductId();
		agentProductBean.setSellerId(parentUserId);
		agentProductBean
				.setSellerLoginId(new DGUserWapper()
						.selectDGUserInfo(createmchBean.getMchId()).get(0)
						.getLoginId());

		agentProductBean.setCurrency(currency);
//		agentProductBean.setGoodsOwnerId(goodsOwnerId);

		return agentProductBean;
	}
	
	/**
	 * 创建渠道商
	 * 
	 * @param parentUserId
	 * @param productId
	 * @param country
	 * @return
	 * @throws Exception
	 */
	public static AgentProductBean createChannel(long parentUserId,
			String productId, String country,
			AgentProductBean goodsOwnerProductBean) throws Exception {

		AgentProductBean agentProductBean = null;

		// 创建一个新的渠道商并绑定上级
		createmchBean createmchBean = DGSQBaseService.bindChannel(
				(int) parentUserId, country, null);
		String currency = getMchInfoBySellerId((long) createmchBean.getMchId())
				.getCurrency();

		// productId = DGSQBaseService.createAgentProduct(parentUserId,
		// autotest_goodsOwnerName, true, currency);

		agentProductBean = DGSQBaseService.importAgentProduct(
				createmchBean.getMchId(), "", productId, (int) parentUserId,
				true);

		parentUserId = createmchBean.getMchId();
		productId = agentProductBean.getProductId();
		agentProductBean.setSellerId(parentUserId);
		agentProductBean
				.setSellerLoginId(new DGUserWapper()
						.selectDGUserInfo(createmchBean.getMchId()).get(0)
						.getLoginId());

		agentProductBean.setCurrency(currency);
		agentProductBean.setGoodsOwnerId(goodsOwnerProductBean.getSellerId());

		return agentProductBean;
	}
	
	/**
	 * 创建渠道商
	 * @param parentUserId
	 * @param productId
	 * @param country
	 * @return
	 * @throws Exception
	 */
	public static AgentProductBean createChannel(long parentUserId,
			String productId, String country, Long sellerId) throws Exception {

		return createChannel(parentUserId, productId, country, sellerId, null);
	}
	
	/**
	 * 创建渠道商
	 * 
	 * @param parentUserId
	 * @param productId
	 * @param country
	 * @return
	 * @throws Exception
	 */
	public static AgentProductBean createChannel(long parentUserId,
			String productId, String country, Long sellerId,
			AgentProductBean goodsOwnerProductBean) throws Exception {

		AgentProductBean agentProductBean = null;

		// 创建一个新的渠道商并绑定上级
		DGSQBaseService.bindChannel((int) parentUserId, country,
				sellerId.intValue());

		String currency = getMchInfoBySellerId(sellerId).getCurrency();

		// productId = DGSQBaseService.createAgentProduct(parentUserId,
		// autotest_goodsOwnerName, true, currency);

		agentProductBean = DGSQBaseService.importAgentProduct(
				sellerId.intValue(), "", productId, (int) parentUserId, true);

		// parentUserId = createmchBean.getMchId();
		productId = agentProductBean.getProductId();
		agentProductBean.setSellerId(sellerId);
		agentProductBean.setSellerLoginId(new DGUserWapper()
				.selectDGUserInfo(sellerId.intValue()).get(0).getLoginId());
		agentProductBean.setGoodsOwnerId(null == goodsOwnerProductBean ? null
				: goodsOwnerProductBean.getSellerId());

		agentProductBean.setCurrency(currency);

		return agentProductBean;
	}
	
	/**
	 * 创建代理商
	 * @param sellerId
	 * @param productId
	 * @return
	 * @throws Exception
	 */
	public static AgentProductBean createAgent(long sellerId, String productId, String country) throws Exception {

		createmchBean bean = DGSQBaseService.createAgent(
				(int)sellerId, country);
		String currency = getMchInfoBySellerId((long) bean.getMchId())
				.getCurrency();

		AgentProductBean agentProduct = DGSQBaseService.importAgentProduct(
				bean.getMchId(), "", productId, (int) sellerId, false);

		agentProduct.setSellerId(bean.getMchId());
		agentProduct.setSellerLoginId(new DGUserWapper()
				.selectDGUserInfo(bean.getMchId()).get(0).getLoginId());
		agentProduct.setCurrency(currency);

		return agentProduct;
	}

	/**
	 * 1个买手,1个商品,生成单个订单
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeOrder(AgentProductBean productBean) throws Exception {

		return placeOrder(productBean, BigDecimal.ZERO);
	}
	
	/**
	 * 1个买手,1个商品,生成单个订单
	 * 
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeOrderWithPayChannelType(
			AgentProductBean productBean, Long goodsOwnerId, Integer payChannelType)
			throws Exception {

		int userId = new OrderCallService().createNewUser();
		
		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(1234, BigDecimal.ZERO, userId,
						productBean, goodsOwnerId, false);
		
		placeOrderReq.setOrderSource(OrderSourceEnum.C2CWechat);
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);

		placeOrderReq.setDiscount(BigDecimal.ZERO);
		placeOrderReq.setPayChannelType(payChannelType);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 1个买手,1个商品,生成单个订单
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeOrderWithUserId(AgentProductBean productBean, Long userId) throws Exception {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(1234, BigDecimal.ZERO, userId,
						productBean, autotest_goodsOwnerId, false);
		
		placeOrderReq.setOrderSource(OrderSourceEnum.C2CWechat);
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 1个买手,1个商品,生成单个神器代理订单
	 * 
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeOrder(AgentProductBean productBean,
			Boolean shenqiProxyOrder) throws Exception {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(1234L, BigDecimal.ZERO, 20238699,
						productBean, autotest_goodsOwnerId);

		placeOrderReq.setShenqiProxyBuyOrder(true);
		placeOrderReq.setShenqiBuyOrderCsId(1235678L);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 下单带有purchaserIdcardId
	 * @return
	 */
	public static TradingServiceResp placeOrderWithPurchaserIdcardId(
			AgentProductBean productBean, Long purchaserIdcardId) {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(1234L, BigDecimal.ZERO, 20238699,
						productBean, autotest_goodsOwnerId);

		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.setPurchaserIdcardId(purchaserIdcardId);
		
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.setShenqiIdCardRequirement(1);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 下单带有WarehouseId
	 * @return
	 */
	public static TradingServiceResp placeOrderWithWarehouseId(
			AgentProductBean productBean, Integer purchaserIdcardId) {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(1234L, BigDecimal.ZERO, 20238699,
						productBean, autotest_goodsOwnerId);

		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.setWarehouseId(purchaserIdcardId);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 1个买手,1个商品,生成单个订单
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeOrder(AgentProductBean productBean,
			Integer customSettlementCurrencyType, Long goodsOwnerId, String currency)
			throws Exception {

		int userId = new OrderCallService().createNewUser();
		
		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(1234, BigDecimal.ZERO, userId,
						productBean, goodsOwnerId, false);
		
		placeOrderReq.setOrderSource(OrderSourceEnum.C2CWechat);
		
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).getOrderItems().get(0).setProdTaxRate(BigDecimal.ZERO);
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);

		placeOrderReq.setCurrency(currency);
		placeOrderReq.setCustomSettlementCurrencyType(customSettlementCurrencyType);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 1个买手,1个商品,生成单个订单
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeOrder(AgentProductBean productBean,
			Integer customSettlementCurrencyType, Integer payChannelType, Long goodsOwnerId, String currency)
			throws Exception {

		int userId = new OrderCallService().createNewUser();
		
		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(1234, BigDecimal.ZERO, userId,
						productBean, goodsOwnerId, false);
		
		placeOrderReq.setPayChannelType(payChannelType);
		
		placeOrderReq.setOrderSource(OrderSourceEnum.C2CWechat);
		
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).getOrderItems().get(0).setProdTaxRate(BigDecimal.ZERO);
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);

		placeOrderReq.setCurrency(currency);
		placeOrderReq.setCustomSettlementCurrencyType(customSettlementCurrencyType);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 1个买手,1个商品,生成单个订单
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static PlaceOrderReq placeOrderOver50000(AgentProductBean productBean,
			Integer payChannelType, Long goodsOwnerId, String currency)
			throws Exception {

		int userId = new OrderCallService().createNewUser();
		
		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(1234, BigDecimal.ZERO, userId,
						productBean, goodsOwnerId, false);
		
		placeOrderReq.setPayChannelType(payChannelType);
		
		placeOrderReq.setOrderSource(OrderSourceEnum.C2CWechat);
		
		OrderItemVo orderItemVo = placeOrderReq.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(0);
		
		if (currency.equalsIgnoreCase("USD")) {
			
			orderItemVo.setProdTaxRate(BigDecimal.ZERO);
			orderItemVo.setProductPrice(new BigDecimal("10000"));
			orderItemVo.setProductNum(1);
		} else {
			
			orderItemVo.setProdTaxRate(BigDecimal.ZERO);
			orderItemVo.setProductPrice(new BigDecimal("10001"));
			orderItemVo.setProductNum(5);
		}
		
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);
		
		placeOrderReq.setCurrency(currency);

		return placeOrderReq;
	}
	
	public static TradingServiceResp callPlaceOrderService(PlaceOrderReq placeOrderReq) {

		PlaceOrderCall placeorderCall = new PlaceOrderCall();

		TradingServiceResp orderResp = new TradingServiceResp();

		placeorderCall.setData(false, placeOrderReq);

		try {

			if (placeOrderReq.getMainOrderId() % 10000 != placeOrderReq
					.getUserId() % 10000) {

				// 设置主单号
				placeOrderReq.setMainOrderId(genMainOrderId(placeOrderReq
						.getUserId()));
			}

			placeorderCall.callService();

			// 如果下单失败，则重试3次，如果依然失败，则抛出exception
			int n = 0;
			retryPlaceOrder(placeorderCall, n);

			long userId = placeOrderReq.getUserId();

			orderResp.setUserId(userId);

			List<Long> orderIds = placeorderCall.getPlaceOrderResp()
					.getOrderIds();

			List<Order> orderList = new ArrayList<Order>();

			for (int i = 0; i < orderIds.size(); i++) {

				Order order = new Order();

				long orderId = orderIds.get(i);

				OrderShardingWapper orderShardingWapper = new OrderShardingWapper();

				OrderPo orderPo = orderShardingWapper
						.selectOrderbyOrderId(orderId);

				List<OrderDetailPo> orderDetailPoList = orderShardingWapper
						.selectOrderDetailbyOrderId(orderId);

				order.setOrderPo(orderPo);
				order.setOrderDetailPoList(orderDetailPoList);

				orderList.add(order);

			}

			if (placeOrderReq.getBizSource() != null) {

				orderResp.setBizId(placeOrderReq.getBizSource().getBizId());
			}

			orderResp.setOrderList(orderList);

			orderResp.setMainOrderId(placeOrderReq.getMainOrderId());

		} catch (Exception e) {

			e.printStackTrace();

		}

		// 下架由下单创建的商品
		Map<Long, List<String>> map = new HashMap<Long, List<String>>();

		placeOrderReq.getOrderGroups().forEach(
				group -> {

					long sellerId = group.getSellerId();

					List<String> proids = Lists.newArrayList();
					if (null != group.getOrders())
						group.getOrders().forEach(
								order -> order.getOrderItems()
										.forEach(
												item -> proids.add(item
														.getProductId())));

					map.put(sellerId, proids);

				});

		map.forEach((k, v) -> {

			try {

				ProductManagerCallServiceV2.batchSetProductOffSale(v,
						k.intValue());

			} catch (Exception e) {

				e.printStackTrace();

				Logger.info("下架由下单创建的商品出现异常！");
			}
		});

		return orderResp;
	}

	/**
	 * 1个买手,1个商品,生成单个订单
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeOrder(AgentProductBean productBean,
			long goodsOwnerId) throws Exception {

		return placeOrder(productBean, BigDecimal.ZERO, goodsOwnerId, null);
	}

	/**
	 * 1个买手,1个商品,生成单个订单
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeOrder(AgentProductBean productBean,
			BigDecimal discount) throws Exception {

		return placeOrder(productBean, discount, autotest_goodsOwnerId, null);
	}

	/**
	 * 1个买手,1个商品,生成单个订单
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeOrder(AgentProductBean productBean,
			BigDecimal discount, long goodsOwnerId, String currency) throws Exception {

		return placeOrder(productBean, discount, goodsOwnerId, currency, null, false);
	}
	
	/**
	 * 1个买手,1个商品,生成单个订单
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeOrder(AgentProductBean productBean,
			BigDecimal discount, long goodsOwnerId, String currency, Boolean supportOfflinePay) throws Exception {

		return placeOrder(productBean, discount, goodsOwnerId, currency, null, supportOfflinePay);
	}
	
	/**
	 * 1个买手,1个商品,生成单个订单
	 * 
	 * @return
	 */
	public static TradingServiceResp placeOrder(AgentProductBean productBean,
			BigDecimal discount, long goodsOwnerId, String currency, BigDecimal taxRate) {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(1234, BigDecimal.ZERO, 20238699,
						productBean, goodsOwnerId);
		
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).getOrderItems().get(0).setProdTaxRate(taxRate);
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);

		placeOrderReq.setDiscount(discount);
		placeOrderReq.setCurrency(currency);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	public static TradingServiceResp placeOrderWithSelfPickup(
			AgentProductBean productBean, Long goodsOwnerId,
			Boolean pickupInStores) {

		return placeOrderWithSelfPickup(productBean, goodsOwnerId, pickupInStores, null);
	}
	
	/**
	 * 1个买手,1个商品,生成自提订单
	 * 
	 * @return
	 */
	public static TradingServiceResp placeOrderWithSelfPickup(
			AgentProductBean productBean, Long goodsOwnerId,
			Boolean pickupInStores, Integer vStockCount) {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(1234, BigDecimal.ZERO, 20238699,
						productBean, goodsOwnerId);
		
		OrderItemVo orderItemVo = placeOrderReq.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(0);
		
		// 实际库存10 + 虚拟库存2
		orderItemVo.setProductNum(10 + (vStockCount == null ? 0 : vStockCount));

		placeOrderReq.setPickupInStores(pickupInStores);
		placeOrderReq
				.setPickupName(TestDataManager.randomStr(5) + "pickupName");
		placeOrderReq.setPickupAddress(TestDataManager.randomStr(5)
				+ "pickupAddress");
		placeOrderReq.setPickupPhone(TestDataManager.getRandomNum(11));
		placeOrderReq.setPickupUserPhone(TestDataManager.getRandomNum(11));

		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 1个买手,1个商品,生成单个订单
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeOrder(AgentProductBean productBean,
			BigDecimal discount, long goodsOwnerId, String currency,
			BigDecimal taxRate, Boolean supportOfflinePay) throws Exception {

		int userId = new OrderCallService().createNewUser();
		
		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(1234, BigDecimal.ZERO, userId,
						productBean, goodsOwnerId, false);
		
		placeOrderReq.setOrderSource(OrderSourceEnum.C2CWechat);
		
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).getOrderItems().get(0).setProdTaxRate(taxRate);
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).setLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);

		placeOrderReq.setDiscount(discount);
		placeOrderReq.setCurrency(currency);
		
		placeOrderReq.setSupportOfflinePay(supportOfflinePay);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 1个买手,1个商品,生成单个订单
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeOrderNegativeProfit(AgentProductBean productBean,
			BigDecimal discount, long goodsOwnerId, String currency,
			BigDecimal taxRate, Boolean supportOfflinePay) throws Exception {

		return placeOrderNegativeProfit(productBean, discount, goodsOwnerId,
				currency, taxRate, supportOfflinePay, null);
	}
	
	/**
	 * 1个买手,1个商品,生成单个订单
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeOrderNegativeProfit(AgentProductBean productBean,
			BigDecimal discount, long goodsOwnerId, String currency,
			BigDecimal taxRate, Boolean supportOfflinePay, Integer payChannelType) throws Exception {

		int userId = new OrderCallService().createNewUser();
		
		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(1234, BigDecimal.ZERO, userId,
						productBean, goodsOwnerId, false);
		
		OrderItemVo orderItemVo1 = placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0);
		orderItemVo1.setProdTaxRate(new BigDecimal("0.17"));
		
		OrderItemVo orderItemVo2 = TradingForDGSQCallService
				.createOrderItemVo(productBean.getProductId(), productBean
						.getCatalogList().get(1));
		orderItemVo2.setProdTaxRate(new BigDecimal("0.47"));

		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().add(orderItemVo2);
		
		BigDecimal discount1 = orderItemVo1.getProductPrice()
				.multiply(new BigDecimal(orderItemVo1.getProductNum()));
		
		BigDecimal discount2 = orderItemVo2.getProductPrice()
				.multiply(new BigDecimal(orderItemVo2.getProductNum()));
		
		// 定义买手下的优惠商品信息list
		List<SellerPromotionVo> sellerPromotionList = new ArrayList<SellerPromotionVo>();

		SellerPromotionVo sellerPromotion1 = new SellerPromotionVo();

		sellerPromotion1.setAmountCondition(new BigDecimal(100));
		sellerPromotion1.setId(123456789);
		sellerPromotion1.setName("自动化商家优惠活动");

		sellerPromotion1.setPromotionValue(new BigDecimal(12));
		sellerPromotion1.setQtyCondition(4);

		sellerPromotion1.setReducedAmount(discount1.add(discount2));
		sellerPromotion1.setType(PromotionTypeEnum.ReduceIfAmountEnough);

		sellerPromotion1.setApportions(Arrays.asList(
				new CatalogApportionVo(productBean
						.getCatalogList().get(0),
						orderItemVo1.getProductNum()),
				new CatalogApportionVo(orderItemVo2.getCatalogId(),
						orderItemVo2.getProductNum())));

		sellerPromotionList.add(sellerPromotion1);

		placeOrderReq.getOrderGroups().get(0)
				.setSellerPromotionApportions(sellerPromotionList);
		placeOrderReq.setCurrency(currency);
		
		if (null != payChannelType)
			placeOrderReq.setPayChannelType(payChannelType);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 1个买手,1个商品,生成带有订单别名单个神器代理订单
	 * 
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeOrderWithOrderAlias(AgentProductBean productBean,
			String orderAlias) throws Exception {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(1234L, BigDecimal.ZERO, 20238699,
						productBean, autotest_goodsOwnerId);

		placeOrderReq.setShenqiProxyBuyOrder(true);
		placeOrderReq.setShenqiBuyOrderCsId(1235678L);
		
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).setOrderAlias(orderAlias);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}

	/**
	 * 1个买手,多个商品,生成1个订单
	 * 
	 * @return
	 */
	public static TradingServiceResp placeOrder1(AgentProductBean productBean) {
		
		return placeOrder1(productBean, null);
	}
	
	/**
	 * 1个买手,多个商品,生成1个订单,包含税费
	 * 
	 * @return
	 */
	public static TradingServiceResp placeOrder1(AgentProductBean productBean, BigDecimal taxRate) {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(0, BigDecimal.ZERO, 20238699,
						productBean, autotest_goodsOwnerId);

		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).getOrderItems().get(0).setProdTaxRate(taxRate);
		
		OrderItemVo orderItemVo = TradingForDGSQCallService
				.createOrderItemVo(productBean.getProductId(), productBean
						.getCatalogList().get(1));
		
		orderItemVo.setProdTaxRate(taxRate);

		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().add(orderItemVo);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}

	/**
	 * 直销商外币下单
	 * 
	 * @return
	 */
	public static TradingServiceResp placeOrder1(AgentProductBean productBean,
			long sellerId, String currency) {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(0, BigDecimal.ZERO, 20238699,
						productBean, sellerId);
		placeOrderReq.setCurrency(currency);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}

	/**
	 * 直销商下单
	 * 
	 * @return
	 */
	public static TradingServiceResp placeOrder1(AgentProductBean productBean,
			long sellerId) {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(0, BigDecimal.ZERO, 20238699,
						productBean, sellerId, true, false);
		
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0).setProdTaxRate(new BigDecimal("0.17"));

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 直销商下单
	 * 
	 * @return
	 */
	public static TradingServiceResp placeOrder1(AgentProductBean productBean,
			long sellerId, Boolean supportOfflinePay) {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(0, BigDecimal.ZERO, 20238699,
						productBean, sellerId, true, supportOfflinePay);
		
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0).setProdTaxRate(new BigDecimal("0.17"));

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 直销商下单
	 * 
	 * @return
	 */
	public static TradingServiceResp placeOrder1(AgentProductBean productBean,
			long sellerId, int vStockCount) {
		
		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(0, BigDecimal.ZERO, 20238699,
						productBean, sellerId, false, false);
		
		OrderItemVo orderItemVo = placeOrderReq.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(0);
		
		// 实际库存10 + 虚拟库存2
		orderItemVo.setProductNum(10 + vStockCount);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 直销商下单
	 * 
	 * @return
	 */
	public static TradingServiceResp placeOrder1(AgentProductBean productBean,
			int sellerId, int vStockCount) {
		
		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(0, BigDecimal.ZERO, 20238699,
						productBean, sellerId, false, false);
		
		OrderItemVo orderItemVo = placeOrderReq.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(0);
		
		// 实际库存10 + 虚拟库存2
		orderItemVo.setProductNum(10 + vStockCount);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}

	/**
	 * 1个买手,多个商品,生成2个订单
	 * 
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeOrder2(BigDecimal discount,
			AgentProductBean productBean, Integer payChannelType) throws Exception {

		return placeOrder2(discount, productBean, null, payChannelType);
	}

	/**
	 * 1个买手,多个商品,生成2个订单
	 * 
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeOrder2(BigDecimal discount,
			AgentProductBean productBean, String currency, Integer payChannelType) throws Exception {

		return placeOrder2(discount, productBean, currency, null, autotest_goodsOwnerId, payChannelType);
	}
	
	/**
	 * 1个买手,多个商品,生成2个订单
	 * 
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeOrder2(BigDecimal discount,
			AgentProductBean productBean, String currency, BigDecimal taxRate, Long goodsOwnerId, Integer payChannelType) throws Exception {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(0, BigDecimal.ZERO, 20238699,
						productBean, goodsOwnerId);
		
//		placeOrderReq.setUserId(25380404);
		
		//设置taxRate
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).getOrderItems().get(0).setProdTaxRate(taxRate);
		
//		placeOrderReq.getOrderGroups().get(0).getOrders().get(0).getOrderItems().get(0).setProductNum(1);

		OrderVo orderVo = createOrderVo(Lists.newArrayList(productBean));
//
		orderVo.getOrderItems().get(0).setProductId(productBean.getProductId());
		orderVo.getOrderItems().get(0)
				.setCatalogId(productBean.getCatalogList().get(1));
		
		orderVo.getOrderItems().get(0).setProductNum(1);
//
		orderVo.setGoodsOwnerId(goodsOwnerId);
		orderVo.setShenqiLogisticsType(100);
		orderVo.setShenqiIdCardRequirement(0);

		placeOrderReq.getOrderGroups().get(0).getOrders().add(orderVo);

		placeOrderReq.setDiscount(discount);
		placeOrderReq.setCurrency(currency);
		
		placeOrderReq.setPayChannelType(payChannelType);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 1个买手,多个商品,生成2个订单
	 * 
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeOrder2(BigDecimal discount,
			AgentProductBean productBean, String currency, BigDecimal taxRate,
			Long goodsOwnerId, Integer customSettlementCurrencyType, Integer payChannelType)
			throws Exception {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(0, BigDecimal.ZERO, 20238699,
						productBean, goodsOwnerId);

		// placeOrderReq.setUserId(25380404);

		// 设置taxRate
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0).setProdTaxRate(taxRate);

		// placeOrderReq.getOrderGroups().get(0).getOrders().get(0).getOrderItems().get(0).setProductNum(1);

		OrderVo orderVo = createOrderVo(Lists.newArrayList(productBean));
		//
		orderVo.getOrderItems().get(0).setProductId(productBean.getProductId());
		orderVo.getOrderItems().get(0)
				.setCatalogId(productBean.getCatalogList().get(1));

		orderVo.getOrderItems().get(0).setProductNum(1);
		//
		orderVo.setGoodsOwnerId(goodsOwnerId);
		orderVo.setShenqiLogisticsType(100);
		orderVo.setShenqiIdCardRequirement(0);

		placeOrderReq.getOrderGroups().get(0).getOrders().add(orderVo);

		placeOrderReq.setDiscount(discount);
		placeOrderReq.setCurrency(currency);

		placeOrderReq
				.setCustomSettlementCurrencyType(customSettlementCurrencyType);
		placeOrderReq.setPayChannelType(payChannelType);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 1个买手,多个商品,包含虚拟库存,生成2个订单
	 * 
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeVStockOrder2(
			AgentProductBean productBean) throws Exception {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(4321, BigDecimal.ZERO, 20238699,
						productBean, (int) autotest_goodsOwnerId);

		OrderItemVo orderItemVo = placeOrderReq.getOrderGroups().get(0)
				.getOrders().get(0).getOrderItems().get(0);

		// 实际库存12 + 虚拟库存2
		orderItemVo.setProductNum(12);
		orderItemVo.setVirtualProductNum(2);

		// 第二个订单
		OrderVo orderVo = TradingForDGSQCallService.createOrderVo(Arrays
				.asList(productBean));

		orderVo.getOrderItems().get(0).setProductNum(1);
		orderVo.getOrderItems().get(0).setVirtualProductNum(1);

		orderVo.setGoodsOwnerId(autotest_goodsOwnerId);

		placeOrderReq.getOrderGroups().get(0).getOrders().add(orderVo);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}

	/**
	 * 2个买手,多个商品,生成2个订单
	 * 神器订单不支持多个店铺的订单
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static TradingServiceResp placeOrder3(AgentProductBean productBean,
			long goodsOwnerId) throws Exception {

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(0, BigDecimal.ZERO, 20238699,
						productBean, goodsOwnerId);

		createmchBean createmchBean = GodmchManageCallService
				.InitcreatemchBeanForChannel(DGSQBaseService.createGoodsOwner("USA"));

		AgentProductBean productBean2 = TradingForDGSQCallService
				.createProxychain(createmchBean.getMchId(), 0, false);

		OrderGroupVo orderGroupVo = TradingForDGSQCallService
				.createOrderGroupVo(productBean2, createmchBean.getMchId());

		placeOrderReq.getOrderGroups().add(orderGroupVo);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 继承代理订单
	 * @param productBean
	 * @param goodsOwnerId
	 * @param salesman
	 * @param isPromotion
	 * @return
	 */
	public static TradingServiceResp placeInheritedOrder(AgentProductBean productBean,
			long goodsOwnerId, long salesman, boolean isPromotion) {
		
		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(salesman, BigDecimal.ZERO, 20238699,
						productBean, goodsOwnerId, isPromotion, false);
		
		OrderItemVo orderItemVo1 = placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0);
		orderItemVo1.setProdTaxRate(new BigDecimal("0.17"));
		orderItemVo1.setProductPrice(new BigDecimal("100.00"));
		orderItemVo1.setProductNum(1);

		if (isPromotion) {
			
			// 定义买手下的优惠商品信息list
			List<SellerPromotionVo> sellerPromotionList = new ArrayList<SellerPromotionVo>();

			SellerPromotionVo sellerPromotion1 = new SellerPromotionVo();

			sellerPromotion1.setAmountCondition(new BigDecimal(100));
			sellerPromotion1.setId(123456789);
			sellerPromotion1.setName("自动化商家优惠活动");

			sellerPromotion1.setPromotionValue(new BigDecimal(12));
			sellerPromotion1.setQtyCondition(4);

			sellerPromotion1.setReducedAmount(new BigDecimal(15));
			sellerPromotion1.setType(PromotionTypeEnum.ReduceIfAmountEnough);

			sellerPromotion1.setApportions(Arrays
					.asList(new CatalogApportionVo(productBean.getCatalogList()
							.get(0), orderItemVo1.getProductNum())));

			sellerPromotionList.add(sellerPromotion1);

			placeOrderReq.getOrderGroups().get(0)
					.setSellerPromotionApportions(sellerPromotionList);
		}
		
		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 继承代理多商品订单
	 * @param productBean
	 * @param goodsOwnerId
	 * @param salesman
	 * @param isPromotion
	 * @return
	 */
	public static TradingServiceResp placeInheritedOrderMultiProduct(AgentProductBean productBean,
			long goodsOwnerId, long salesman, boolean isPromotion) {
		
		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(salesman, BigDecimal.ZERO, 20238699,
						productBean, goodsOwnerId, isPromotion, false);
		
		OrderItemVo orderItemVo1 = placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0);
		orderItemVo1.setProdTaxRate(new BigDecimal("0.17"));
		orderItemVo1.setProductPrice(new BigDecimal("165.00"));
		orderItemVo1.setProductNum(1);
		
		OrderItemVo orderItemVo2 = TradingForDGSQCallService
				.createOrderItemVo(productBean.getProductId(), productBean
						.getCatalogList().get(1));
		orderItemVo2.setProdTaxRate(new BigDecimal("0.47"));
		orderItemVo2.setProductPrice(new BigDecimal("168.00"));
		orderItemVo2.setProductNum(1);

		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().add(orderItemVo2);
		
		if (isPromotion) {
			
			// 定义买手下的优惠商品信息list
			List<SellerPromotionVo> sellerPromotionList = new ArrayList<SellerPromotionVo>();

			SellerPromotionVo sellerPromotion1 = new SellerPromotionVo();

			sellerPromotion1.setAmountCondition(new BigDecimal(100));
			sellerPromotion1.setId(123456789);
			sellerPromotion1.setName("自动化商家优惠活动");

			sellerPromotion1.setPromotionValue(new BigDecimal(12));
			sellerPromotion1.setQtyCondition(4);

			sellerPromotion1.setReducedAmount(new BigDecimal(15));
			sellerPromotion1.setType(PromotionTypeEnum.ReduceIfAmountEnough);

			sellerPromotion1.setApportions(Arrays.asList(
					new CatalogApportionVo(productBean.getCatalogList().get(0),
							orderItemVo1.getProductNum()),
					new CatalogApportionVo(orderItemVo2.getCatalogId(),
							orderItemVo2.getProductNum())));

			sellerPromotionList.add(sellerPromotion1);

			placeOrderReq.getOrderGroups().get(0)
					.setSellerPromotionApportions(sellerPromotionList);
		}
		
		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	public static TradingServiceResp placeOrderWithSuppliers(Long supplier_1,
			int supplier_count_1, Long supplier_2, int supplier_count_2)
			throws Exception {

		return placeOrderWithSuppliers(supplier_1, supplier_count_1,
				supplier_2, supplier_count_2, null);
	}
	
	/**
	 * 单买手,多商品，多货头,生成多个订单
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeOrderWithSuppliers(Long supplier_1,
			int supplier_count_1, Long supplier_2, int supplier_count_2, Integer payChannelType)
			throws Exception {

		int userId = new OrderCallService().createNewUser();

		// 美元货头
		AgentProductBean supplierProductBean_1 = TradingForDGSQCallService
				.createGoodsOwnerProduct(supplier_1, "CNY", false);

		AgentProductBean productBean_1 = TradingForDGSQCallService
				.createChannel(supplierProductBean_1.getSellerId(),
						supplierProductBean_1.getProductId(), "HKG");

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(0, BigDecimal.ZERO, userId,
						productBean_1, autotest_goodsOwnerId);
		
		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0).setProductNum(supplier_count_1);

		AgentProductBean supplierProductBean_2 = TradingForDGSQCallService
				.createGoodsOwnerProduct(supplier_2, "CNY", false);

		AgentProductBean productBean_2 = TradingForDGSQCallService
				.createChannel(supplierProductBean_2.getSellerId(),
						supplierProductBean_2.getProductId(),
						productBean_1.getCurrency(),
						productBean_1.getSellerId());

		OrderVo orderVo = TradingForDGSQCallService.createOrderVo(Lists
				.newArrayList(productBean_2));

		orderVo.getOrderItems().get(0)
				.setProductId(productBean_2.getProductId());
		orderVo.getOrderItems().get(0)
				.setCatalogId(productBean_2.getCatalogList().get(0));
		orderVo.getOrderItems().get(0).setProductNum(supplier_count_2);

		orderVo.setGoodsOwnerId(supplierProductBean_2.getSellerId());
		orderVo.setShenqiLogisticsType(100);
		orderVo.setShenqiIdCardRequirement(0);

		if (null != payChannelType)
			placeOrderReq.setPayChannelType(payChannelType);
		placeOrderReq.getOrderGroups().get(0).getOrders().add(orderVo);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 单买手,多商品，多货头,生成多个订单
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeOrderWithTwoSuppliers(AgentProductBean supplier_1,
			int supplier_count_1, AgentProductBean supplier_2, int supplier_count_2)
			throws Exception {

		return placeOrderWithTwoSuppliers(supplier_1, supplier_count_1,
				supplier_2, supplier_count_2, null, null);
	}
	
	/**
	 * 单买手,多商品，多货头,生成多个订单
	 * 
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeOrderWithTwoSuppliers(
			AgentProductBean supplier_1, int supplier_count_1,
			AgentProductBean supplier_2, int supplier_count_2, String currency,
			Integer payChannelType) throws Exception {

		int userId = new OrderCallService().createNewUser();

		PlaceOrderReq placeOrderReq = TradingForDGSQCallService
				.buildDGSQStandPlaceOrderReq(0, BigDecimal.ZERO, userId,
						supplier_1, supplier_1.getGoodsOwnerId());

		placeOrderReq.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0).setProductNum(supplier_count_1);

		OrderVo orderVo = TradingForDGSQCallService.createOrderVo(Lists
				.newArrayList(supplier_2));

		orderVo.getOrderItems().get(0).setProductId(supplier_2.getProductId());
		orderVo.getOrderItems().get(0)
				.setCatalogId(supplier_2.getCatalogList().get(0));
		orderVo.getOrderItems().get(0).setProductNum(supplier_count_2);

		orderVo.setGoodsOwnerId(supplier_2.getGoodsOwnerId());
		orderVo.setShenqiLogisticsType(100);
		orderVo.setShenqiIdCardRequirement(0);

		placeOrderReq.setCurrency(currency);
		
		if (null != payChannelType)
			placeOrderReq.setPayChannelType(payChannelType);
		
		placeOrderReq.getOrderGroups().get(0).getOrders().add(orderVo);

		return TradingCallService.callPlaceOrderService(placeOrderReq);
	}
	
	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param tradingId
	 */
	public static Long payOrder(long userId, long tradingId) {

		return payOrder(userId, tradingId, "wxsqBuyer");
	}
	
	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param tradingId
	 */
	public static Long payOrder(long userId, long tradingId, String shenqiMpId) {

		return payOrder(userId, tradingId, shenqiMpId, "6000");
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param tradingId
	 * @param shenqiMpId
	 */
	public static Long payOrder(long userId, long tradingId, String shenqiMpId, String payType) {

		PayReq payReq = new PayReq();

		PayReqCall payReqCall = new PayReqCall();

		long thirdTradingId = 0;

		// 参数
		String tradingPassword = "abc123";
		payReq.setTradingId(tradingId);
		payReq.setUserId(userId);
		payReq.setTradingPwd(tradingPassword);
		payReq.setUserIp("103.84.20.0");
		payReq.setBankId("123");
		payReq.setPayType(payType);
		payReq.setOpenId(isShengPay(payType) ? PayGateWayCallService.SFTWxOpenId
				: PayGateWayCallService.HipoPayWxAppOpenId);
		payReq.setParamExt("");
		payReq.setMemo("备注");
		payReq.setShenqiMpId(shenqiMpId);

		payReqCall.setData(false, payReq);

		try {

			Logger.comment(String.format("用户  %s , 订单支付,交易号 %s", userId,
					tradingId));

			payReqCall.callService();

			thirdTradingId = payReqCall.getData().getLong("tradingId");

			if (payReqCall.getData().optString("errorMessage")
					.equalsIgnoreCase("账户金额不足")) {

				String accountid1 = AccountCallServiceV2
						.getAccountId((int) userId);
				AccountCallServiceV2.resetAccount(accountid1, new BigDecimal(
						9000000), new BigDecimal(0));

				payOrder(userId, tradingId, shenqiMpId);
			}
		} catch (Exception e) {
			Logger.info(e.toString());
			Logger.info(String.format("########支付订单 交易号:%s 异常", tradingId));
		}

		return thirdTradingId;
	}
	
	/**
	 * 判断是否盛付通支付
	 * @param payType
	 * @return
	 */
	public static boolean isShengPay(String payType) {
		
		if (null == payType)
			return false;
		else if (payType.equalsIgnoreCase("6010") || payType.equalsIgnoreCase("6011"))
			return true;
		else
			return false;
	}

	/**
	 * 取消订单
	 * 
	 * @param orderId
	 * @param type
	 * @param userId
	 */
	public static CancelOrderCall cancelOrder(long orderId,
			CancelOrderTypeEnum type, long userId) {

		CancelOrderReq cancelorderReq = new CancelOrderReq();
		CancelOrderCall cancelordercall = new CancelOrderCall();

		cancelorderReq.setCancelReason("自动化测试取消订单");
		cancelorderReq.setCancelType(type);
		cancelorderReq.setOrderId(orderId);
		cancelorderReq.setUserId(userId);

		cancelordercall.setData(false, cancelorderReq);
		try {

			cancelordercall.callService();

		} catch (Exception e) {
			Logger.info(String.format("########取消订单:%s 异常", orderId));
		}

		return cancelordercall;
	}

	public static String delivery(long goodsOwnerId, long orderId, Long csId, Integer partialDeliveryStatus)
			throws ClientProtocolException, IOException {

		SqDeliveryReq deliveryReq = new SqDeliveryReq();
		SqDeliveryCall deliveryCall = new SqDeliveryCall();
		DeliveryInfo dInfo = new DeliveryInfo();
		String billNo = TestDataManager.getRandomNum(13);

		dInfo.setOrderId(orderId);

		dInfo.setBillNo(billNo);

		// 发货节点、1国际段,2转运段,3国内段
		dInfo.setDeliverySection(1);
		dInfo.setDeliverySource(1);

		dInfo.setExpressName("sf");
		dInfo.setYmtExpressCode("Y013");
		dInfo.setPartialDeliveryStatus(partialDeliveryStatus);

		deliveryReq.setDeliveryInfos(Lists.newArrayList(dInfo));

		deliveryReq.setGoodsOwnerId(goodsOwnerId);
		deliveryReq.setCdId(csId);

		deliveryCall.setData(deliveryReq);
		deliveryCall.callService();

		return billNo;
	}

	/**
	 * 操作买手备注
	 * 
	 * @param orderId
	 * @param sellerId
	 * @param type
	 *            (0:添加日志，1：更新日志)
	 * @return
	 */
	public static void operateSellerMemo(long orderId, long sellerId, int type)
			throws ClientProtocolException, IOException {

		if (type == 0) {

			AddSellerMemoReq addSellerMemoReq = new AddSellerMemoReq();
			AddSellerMemoCall addSellerMemoCall = new AddSellerMemoCall();

			addSellerMemoReq.setOrderId(orderId);
			addSellerMemoReq.setSellerId(sellerId);
			addSellerMemoReq.setSellerMemo(TestDataManager.randomStr(30)
					+ "阿斯达");
			addSellerMemoReq.setOperatorId(1);

			addSellerMemoCall.setData(addSellerMemoReq);
			addSellerMemoCall.callService();

		} else {

			UpdateShenQiSellerMemoReq updateShenQiSellerMemoReq = new UpdateShenQiSellerMemoReq();
			UpdateShenQiSellerMemoCall updateShenQiSellerMemoCall = new UpdateShenQiSellerMemoCall();

			updateShenQiSellerMemoReq.setOrderId(orderId);
			updateShenQiSellerMemoReq.setSellerId(sellerId);
			updateShenQiSellerMemoReq.setSellerMemo(TestDataManager
					.randomStr(30) + "阿斯达");
			updateShenQiSellerMemoReq.setOperatorId(1);

			updateShenQiSellerMemoCall.setData(updateShenQiSellerMemoReq);
			updateShenQiSellerMemoCall.callService();
		}
	}

	/**
	 * 根據userid 生成主单号
	 * 
	 * @param userId
	 * @return
	 */
	public static Long genMainOrderId(long userId) {

		long last4 = userId % 10000;

		GetSeqReq req = new GetSeqReq();
		GetSeqIdsCall call = new GetSeqIdsCall();

		long nativeId = 0L;

		req.setCount(1);
		req.setSeqName(String.format("main_%s", last4));

		call.setData(false, req);

		try {
			call.callService();

		} catch (Exception e) {

			e.printStackTrace();
		}

		nativeId = call.getids().get(0);

		nativeId += 100000;

		return nativeId * 10000 + last4;
	}

	/**
	 * 修改订单价格
	 * 
	 * @param orderId
	 * @param sellerId
	 * @param discount
	 * @param freight
	 */
	public static void changeDiscount(long orderId, long sellerId,
			BigDecimal discount, BigDecimal freight) {

		try {
			Logger.comment("开始修改订单折扣");
			ChangeOrderDiscountReq changeOrderDiscountReq = new ChangeOrderDiscountReq();
			ChangeOrderDiscountCall changeOrderDiscountCall = new ChangeOrderDiscountCall();

			changeOrderDiscountReq.setDiscount(discount);

			changeOrderDiscountReq.setFreight(freight);
			changeOrderDiscountReq.setOrderId(orderId);
			changeOrderDiscountReq.setSellerId(sellerId);

			// 发送请求
			changeOrderDiscountCall.setData(changeOrderDiscountReq);

			changeOrderDiscountCall.callService();

			Logger.comment("结束修改订单折扣");
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 根據mchId 获取渠道商信息
	 * 
	 * @param mchId
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static MchInfoVo getMchInfoBySellerId(Long mchId) throws ClientProtocolException, IOException {

		detailmchBean detailmchbean = new detailmchBean();
		detailmchCall detailmchcall = new detailmchCall();
		
		detailmchbean.setMchId(mchId.intValue()); 

		detailmchcall.setData(detailmchbean);
		detailmchcall.callService();
		
		return detailmchcall.getResult();
	}

	/**
	 * 判断是否为自动继承代理
	 * @param sellerId
	 * @return
	 */
	public static Boolean isInheritedAgent(long sellerId) {
		
		int agentMode = 0;

		YmatouEasyCall mchDetailCall = new YmatouEasyCall("", "GET", "JSON");

		mchDetailCall
				.setUrl("http://godmch.iapi.ymatou.com/api/mch/detail?mchId="
						+ sellerId);

		try {
			mchDetailCall.callService();

			JSONObject data = new JSONObject(mchDetailCall.getReturnData())
					.optJSONObject("result");

			if (null == data)
				return false;
			else {

				agentMode = data.optInt("agentMode");
			}

		} catch (Exception e) {

			e.printStackTrace();
		}

		return agentMode == 2 ? true : false;
	}
	
	/**
	 * 根據sellerid 获取sellerid对应的币种
	 * 
	 * @param sellerId
	 * @return
	 */
	public static int getAllParents(long sellerId) {

		int parentId = 0;

		YmatouEasyCall mchDetailCall = new YmatouEasyCall("", "GET", "JSON");

		mchDetailCall
				.setUrl("http://godmch.iapi.ymatou.com/api/mch/allparents?mchId="
						+ sellerId);

		try {
			mchDetailCall.callService();

			JSONObject data = new JSONObject(mchDetailCall.getReturnData())
					.optJSONObject("result");

			if (null == data)
				return 0;
			else {

				Logger.debug("returndata:" + data);

				parentId = data.optJSONArray("parents").getJSONObject(0)
						.optInt("parentMchId");
			}

		} catch (Exception e) {

			e.printStackTrace();
		}

		return parentId;
	}

	/**
	 * 代购神器订单结算job
	 * 
	 * @param sellerId
	 * @return
	 */
	public static void doSettlement() {

		YmatouEasyCall mchDetailCall = new YmatouEasyCall("", "POST", "JSON");

		mchDetailCall
				.setUrl("http://shenqisettlement.iapi.ymatou.com/api/doSettlement");

		mchDetailCall.setData("{}");

		try {
			mchDetailCall.callService();

			Logger.comment(mchDetailCall.getReturnData());

		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	/**
	 * 客服绑定
	 * 
	 * @param mchId
	 *            商户Id
	 * @param template
	 *            客服权限：1（基本权限），4（所有权限）
	 * @return
	 * @throws Exception
	 */
	public static int bindClientService(long mchId, int template) {

		int csId = 0;

		try {
			UserCreateBean usercreateBean = DGUserCallService
					.initCsUsercreateBean();
			csId = DGUserCallService.UserCreateCall(usercreateBean);
			GodmchManageCallService.CreateCSCall((int) mchId, csId, template);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Logger.comment("创建渠道商客服:" + csId);

		return csId;
	}

	public static BigDecimal calRealForeignAmount(BigDecimal realPayAmount,
			BigDecimal payableAmount, BigDecimal foreignAmount) {

		return realPayAmount.divide(payableAmount, MathContext.DECIMAL32)
				.multiply(foreignAmount);
	}

	/**
	 * 通过买入/卖出币种，进行汇率换算
	 * 
	 * @param sellAmount
	 *            卖出的价格
	 * @param buyCurrency
	 *            买入币种
	 * @param sellCurrency
	 *            卖出币种
	 * @return
	 * @throws Exception
	 */
	public static HashMap<String, BigDecimal> getAmountByCurrency(BigDecimal sellAmount,
			String buyCurrency, String sellCurrency) {

		// 先更新费率
		refreshExchangeRateConfig();

		String exchangeRate = "";
		BigDecimal amount = BigDecimal.ZERO;
		BigDecimal settleRate = BigDecimal.ZERO;
		CurrencyConfigWrapper wrapper = new CurrencyConfigWrapper();
		CurrencyConfig currencyConfig = wrapper
				.selectByPrimaryKey(sellCurrency);

		if (buyCurrency.equalsIgnoreCase("CNY"))
			exchangeRate = currencyConfig.getExchange_rmb_original_value();
		else
			exchangeRate = currencyConfig.getExchange_usd_original_value();

		String[] exhangeRateRatio = exchangeRate.split(" ");
		String currencyRatio = exhangeRateRatio[0];
		String priceRatio = exhangeRateRatio[1];

		String[] currencyRatioArray = currencyRatio.split("/");
		String[] priceRatioArray = priceRatio.split("/");
		String currencyRatioArrayLeft = currencyRatioArray[0];

		if (buyCurrency.equalsIgnoreCase(currencyRatioArrayLeft)) {
			
			amount = sellAmount.divide(new BigDecimal(priceRatioArray[1]), 2,
					RoundingMode.DOWN);
			settleRate = BigDecimal.ONE.divide(new BigDecimal(priceRatioArray[1]), 6,
					RoundingMode.HALF_DOWN);
		}
		else {
			
			amount = sellAmount.multiply(new BigDecimal(priceRatioArray[0]))
					.setScale(2, RoundingMode.HALF_DOWN);
			settleRate = new BigDecimal(priceRatioArray[0]);
		}
		
		HashMap<String, BigDecimal> map = new HashMap<String, BigDecimal>();
		
		map.put("amount", amount);
		map.put("settleRate", settleRate);
			
		return map;
	}

	/**
	 * 更新最新汇率
	 * 
	 * @return
	 */
	public static void refreshExchangeRateConfig() {

		YmatouEasyCall mchDetailCall = new YmatouEasyCall("", "POST", "JSON");

		mchDetailCall
				.setUrl("http://shenqisettlement.iapi.ymatou.com/api/executeRefreshExchangeRateConfigTask");

		mchDetailCall.setData("{}");

		try {
			mchDetailCall.callService();

			Logger.comment(mchDetailCall.getReturnData());

		} catch (Exception e) {

			e.printStackTrace();
		}
	}
	
	/**
	 * 生成账户账单
	 * 
	 * @return
	 */
	public static void generateAccountDataPerDay() {

		YmatouEasyCall generateAccountDataPerDayCall = new YmatouEasyCall("", "POST", "JSON");

		generateAccountDataPerDayCall
				.setUrl("http://shenqisettlement.iapi.ymatou.com/api/generateAccountDataPerDay");

		generateAccountDataPerDayCall.setData("{}");

		try {
			generateAccountDataPerDayCall.callService();

			Logger.comment(generateAccountDataPerDayCall.getReturnData());

		} catch (Exception e) {

			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @param userId
	 *            用户买家id
	 * @param sellerId
	 *            商家卖家id
	 * @param orderAmount
	 *            订单满多少
	 * @param sellerCouponValue
	 *            优惠券减多少
	 * @return CouponVo
	 */
	public static CouponVo createSellerCouponVo(Long userId, Long sellerId,
			BigDecimal orderAmount, BigDecimal sellerCouponValue) {

		String sellerCouponCode = TradingForDGSQCallService.receiveSellerCoupon(
				userId, sellerId, orderAmount, sellerCouponValue);

		if (StringUtils.isEmpty(sellerCouponCode)) {
			return null;
		}

		return createCouponVo(sellerCouponCode, sellerCouponValue);

	}
	
	/**
	 * createCouponVo
	 * 
	 * @return CouponVo
	 */
	public static CouponVo createCouponVo(String couponCode,
			BigDecimal couponValue) {

		CouponVo coupon = new CouponVo();

		coupon.setApplianceType(CouponApplianceTypeEnum.ALL);
		coupon.setCouponCode(couponCode);
		coupon.setCouponValue(couponValue);

		return coupon;

	}
	
	/**
	 * 领用商家优惠券
	 * 
	 * @param userId
	 * @param sellerId
	 * @param orderAmount
	 *            订单金额
	 * @param sellerCouponValue
	 *            优惠券减免金额
	 * @return
	 */
	public static String receiveSellerCoupon(Long userId, Long sellerId,
			BigDecimal orderAmount, BigDecimal sellerCouponValue) {

		return CouponShop2cnMCallService.receiveSellerCoupon(userId,
				sellerId, orderAmount, sellerCouponValue);
	}
	
	/**
	 * 订单线下支付确认
	 * @param orderId
	 * @param sellerId
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void confirmOfflinePay(long orderId, long sellerId) throws ClientProtocolException, IOException {
		
		ConfirmOfflinePayReq req = new ConfirmOfflinePayReq();
		
		req.setOrderId(orderId);
		req.setSellerId(sellerId);
		req.setCsId(1234L);
		
		ConfirmOfflinePayCall call = new ConfirmOfflinePayCall();
		
		call.setData(req);
		call.callService();
	}
	
	/**
	 * 设置用户平台费率
	 * 
	 * @return
	 */
	public static void setUserPlatformFeeSetting(Long userId, int rateId) {

		// 如果当前用户存在费率，则设置费率
		if (isExistPlatformFee(userId))
			return;
		else {
			
			YmatouEasyCall setUserPlatformFeeSettingCall = new YmatouEasyCall("", "POST", "JSON");
			StringBuilder setUserPlatformFeeSettingString = new StringBuilder();

			setUserPlatformFeeSettingString.append("{\"userId\":" + userId);
			setUserPlatformFeeSettingString.append(", \"rateId\":" + rateId + "}");
			
			setUserPlatformFeeSettingCall
					.setUrl("http://shenqisettlement.iapi.ymatou.com/api/setUserPlatformFeeSetting");

			setUserPlatformFeeSettingCall.setData(setUserPlatformFeeSettingString.toString());

			try {
				setUserPlatformFeeSettingCall.callService();

				Logger.comment(setUserPlatformFeeSettingCall.getReturnData());

			} catch (Exception e) {

				e.printStackTrace();
			}
		}
	}
	
	public static boolean isExistPlatformFee(long userId) {
		
		YmatouEasyCall getSellAmountListCall = new YmatouEasyCall("", "POST", "JSON");
		StringBuilder getSellAmountListString = new StringBuilder();

		getSellAmountListString.append("{\"userIdList\":[" + userId + "]}");
		
		getSellAmountListCall
				.setUrl("http://shenqisettlement.iapi.ymatou.com/api/getSellAmountList");

		getSellAmountListCall.setData(getSellAmountListString.toString());

		try {
			getSellAmountListCall.callService();

			Logger.comment(getSellAmountListCall.getReturnData());
			
			JSONObject sellAmountVo = new JSONObject(
					getSellAmountListCall.getReturnData())
					.optJSONObject("result").optJSONArray("sellAmountVoList").getJSONObject(0);
			
			Double directSellRate = sellAmountVo.getDouble("directSellRate");
			Double proxySellRate = sellAmountVo.getDouble("proxySellRate");
			
			// 如果不等于默认费率，则当前用户存在费率
			if (Utils.zeroIfNull(directSellRate) != 1.2 && Utils.zeroIfNull(proxySellRate) != 1.6)
				return true;
			else
				return false;

		} catch (Exception e) {

			e.printStackTrace();
			return false;
		}
	}
	
	public static ProductDetailsDto getProductDetails(Long userId,
			String productId) throws ClientProtocolException, IOException {

		ProductDetailsBean productDetailsBean = new ProductDetailsBean();
		ProductDetailsCall productdetailsCall = new ProductDetailsCall();

		productDetailsBean.setProductId(productId);
		productDetailsBean.setUserId(userId.intValue());

		productdetailsCall.setData(productDetailsBean);
		productdetailsCall.callService();

		String product = productdetailsCall.getJsonObject().get("data")
				.toString();

		ProductDetailsDto productDetailsDto = (ProductDetailsDto) FormatUtil
				.GSONToObject(product, ProductDetailsDto.class);

		return productDetailsDto;
	}
	
	/**
	 * 创建独立代理链并将商品import给各个代理商
	 * 
	 * @param goodsOwnerId
	 *            货头Id
	 * @param n
	 *            n个中间商
	 * @param needAgent
	 *            是否再添加一个代理
	 * @param isForeignCurrency
	 *            是否使用外币
	 * @return AgentProductBean
	 * @throws Exception
	 */
	public static AgentProductBean createIndependenceProxychain(int goodsOwnerId, int n,
			boolean needAgent, boolean isForeignCurrency) throws Exception {

		AgentProductBean agentProductBean = null;
		int parentUserId = goodsOwnerId;
		String productId = "";
		String currency = "";

		if (!isForeignCurrency) {
			currency = "CNY";
			productId = DGSQBaseService.createAgentProduct(goodsOwnerId,
					autotest_goodsOwnerName, true, currency);
		} else {
			
			currency = getMchInfoBySellerId((long)goodsOwnerId).getCurrency();
			productId = DGSQBaseService.createAgentProduct(goodsOwnerId,
					autotest_goodsOwnerName, true, currency);
		}

		for (int i = 0; i < n; i++) {

			// 创建一个新的渠道商并绑定上级
			createmchBean createmchBean = DGSQBaseService
					.bindChannel(parentUserId);

			agentProductBean = DGSQBaseService
					.importAgentProduct(createmchBean.getMchId(), "",
							productId, parentUserId, true);

			if (needAgent && i == n - 1) {

				createmchBean bean = DGSQBaseService.createAgent(
						createmchBean.getMchId(), "CHN");

				AgentProductBean agentProduct = DGSQBaseService
						.importAgentProduct(bean.getMchId(), "",
								agentProductBean.getProductId(),
								createmchBean.getMchId(), false);

				agentProduct.setSellerId(bean.getMchId());
				agentProduct.setSellerLoginId(new DGUserWapper()
						.selectDGUserInfo(bean.getMchId()).get(0).getLoginId());
				agentProduct.setCurrency(currency);

				return agentProduct;
			}

			parentUserId = createmchBean.getMchId();
			productId = agentProductBean.getProductId();
			agentProductBean.setSellerId(parentUserId);
			agentProductBean.setSellerLoginId(new DGUserWapper()
					.selectDGUserInfo(createmchBean.getMchId()).get(0)
					.getLoginId());
		}

		agentProductBean.setCurrency(currency);

		return agentProductBean;
	}
	
	/**
	 * 创建盛付通代理链并将商品import给各个代理商
	 * 
	 * @param goodsOwnerId
	 *            货头Id
	 * @param n
	 *            n个中间商
	 * @param allShengPay
	 *            是否全部开通盛付通
	 * @return AgentProductBean
	 * @throws Exception
	 */
	public static AgentProductBean createShengPayProxychain(int goodsOwnerId,
			int n) throws Exception {

		AgentProductBean agentProductBean = null;
		int parentUserId = goodsOwnerId;
		String productId = "";
		
		String currency = "CNY";
		productId = DGSQBaseService.createAgentProduct(goodsOwnerId,
				autotest_goodsOwnerName, true, currency);
		
		if (n == 0) {
			
			agentProductBean = new AgentProductBean();
			
			agentProductBean.setSellerId(parentUserId);
			agentProductBean.setSellerLoginId(new DGUserWapper().selectDGUserInfo(
					parentUserId).get(0).getLoginId());
			agentProductBean.setProductId(productId);
			agentProductBean.setRootProductId(productId);
			agentProductBean.setCatalogList(DGSQBaseService.getCatalogIdList(productId));
			agentProductBean.setRootCatalogList(DGSQBaseService.getCatalogIdList(productId));
		}

		for (int i = 0; i < n; i++) {

			// 创建一个新的渠道商并绑定上级
			createmchBean createmchBean = DGSQBaseService
					.bindShengPayChannel(parentUserId, null);

			agentProductBean = DGSQBaseService
					.importAgentProduct(createmchBean.getMchId(), "",
							productId, parentUserId, true);
			
			parentUserId = createmchBean.getMchId();
			productId = agentProductBean.getProductId();
			agentProductBean.setSellerId(parentUserId);
			agentProductBean.setSellerLoginId(new DGUserWapper()
					.selectDGUserInfo(createmchBean.getMchId()).get(0)
					.getLoginId());
		}

		agentProductBean.setCurrency(currency);

		return agentProductBean;
	}
	
	/**
	 * 创建白名单商户代理链并将商品import给各个代理商
	 * 
	 * @param goodsOwnerId
	 *            货头Id
	 * @param isForeignCurrency
	 *            是否使用外币
	 * @return AgentProductBean
	 * @throws Exception
	 */
	public static AgentProductBean createWhiteMerchantProxychain(
			int goodsOwnerId, boolean isForeignCurrency)
			throws Exception {
		
		AgentProductBean agentProductBean = new AgentProductBean();

		String productId = "";
		String currency = "";
		
		if (!isForeignCurrency) {
			currency = "CNY";
			productId = DGSQBaseService.createAgentProduct(goodsOwnerId,
					autotest_goodsOwnerName, true, currency);
		} else {
			
			currency = getMchInfoBySellerId((long)goodsOwnerId).getCurrency();
			productId = DGSQBaseService.createAgentProduct(goodsOwnerId,
					autotest_goodsOwnerName, true, currency);
		}

		agentProductBean.setProductId(productId);
		agentProductBean.setSellerId(goodsOwnerId);
		agentProductBean.setSellerLoginId(new DGUserWapper()
				.selectDGUserInfo(goodsOwnerId).get(0).getLoginId());
		agentProductBean.setCatalogList(DGSQBaseService
				.getCatalogIdList(productId));
		agentProductBean.setCurrency(currency);

		return agentProductBean;
	}
	
	/**
	 * 创建盛付通白名单代理链并将商品import给各个代理商
	 * 
	 * @param goodsOwnerId
	 *            货头Id
	 * @param n
	 *            n个中间商
	 * @return AgentProductBean
	 * @throws Exception
	 */
	public static AgentProductBean createShengPayWhiteMerchantProxychain(int goodsOwnerId,
			int n) throws Exception {

		AgentProductBean agentProductBean = null;
		int parentUserId = goodsOwnerId;
		String productId = "";
		
		String currency = "CNY";
		productId = DGSQBaseService.createAgentProduct(goodsOwnerId,
				autotest_goodsOwnerName, true, currency);

		for (int i = 0; i < n; i++) {

			// 创建一个新的渠道商并绑定上级
			createmchBean createmchBean = DGSQBaseService
					.bindShengPayChannel(parentUserId, null);

			agentProductBean = DGSQBaseService
					.importAgentProduct(createmchBean.getMchId(), "",
							productId, parentUserId, true);
			
			if (i == 0) {
				
				// 设置下级费率百分比
				TradingForDGSQCallService.setAgentRate(goodsOwnerId,
						403855, new BigDecimal("15"));
			}
			
			parentUserId = createmchBean.getMchId();
			productId = agentProductBean.getProductId();
			agentProductBean.setSellerId(parentUserId);
			agentProductBean.setSellerLoginId(new DGUserWapper()
					.selectDGUserInfo(createmchBean.getMchId()).get(0)
					.getLoginId());
		}

		agentProductBean.setCurrency(currency);

		return agentProductBean;
	}
	
	public static void setAgentRate(long goodsOwnerId, int agentType,
			BigDecimal agentRate) throws ClientProtocolException, IOException {

		YmatouEasyCall setAgentRateCall = new YmatouEasyCall("", "POST", "JSON");
		StringBuilder setAgentRateString = new StringBuilder();

		setAgentRateString.append("{\"agentRateList\":[{\"agentType\":"
				+ agentType + ",");
		setAgentRateString.append("\"agentRate\":" + agentRate + "}],");
		setAgentRateString.append("\"mchId\":" + goodsOwnerId + "}");

		setAgentRateCall
				.setUrl("http://godmch.iapi.ymatou.com/api/agentType/setAgentRate");

		setAgentRateCall.setData(setAgentRateString.toString());

		setAgentRateCall.callService();
	}
	
	public static BigDecimal getAgentRate(long goodsOwnerId, long agentId)
			throws Exception {

		YmatouEasyCall getAgentRateCall = new YmatouEasyCall("", "POST", "JSON");
		StringBuilder getAgentRateString = new StringBuilder();

		getAgentRateString.append("{\"mchId\":" + goodsOwnerId + ",");
		getAgentRateString.append("\"agentId\":" + agentId + "}");

		getAgentRateCall
				.setUrl("http://godmch.iapi.ymatou.com/api/agent/getAgentRate");

		getAgentRateCall.setData(getAgentRateString.toString());

		getAgentRateCall.callService();

		Logger.comment(getAgentRateCall.getReturnData());

		JSONObject result = new JSONObject(getAgentRateCall.getReturnData())
				.optJSONObject("result");

		if (result.isNull("agentRate"))
			return null;
		else {

			return new BigDecimal(result.optString("agentRate")).setScale(2);
		}
	}

	public static void modifyGoodsOwnerProdStock(int goodsOwnerId,
			AgentProductBean agentProductBean, int virtualStock, int totalStock)
			throws InterruptedException, IOException {

		DGSQBaseService.modifyAgentProductBean(goodsOwnerId, "goodsOwnerName",
				true, agentProductBean.getRootProductId(),
				agentProductBean.getCurrency(), virtualStock, totalStock);
	}
	
	/**
	 * 设置货头的支付渠道
	 * 
	 * @param goodsOwnerId
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static void setPayModeBean(long goodsOwnerId)
			throws ClientProtocolException, IOException {

		SetPayModeBean bean = GodmchManageCallService
				.initSetPayModeBean((int) goodsOwnerId);
		bean.setAliPayMode(1);

		// 1 飞界国际 2飞界国际电子商务 3 sft
		bean.setPayMode(1);
		GodmchManageCallService.SetPayModeCall(bean);
		
//		bean.setPayMode(3);
//		GodmchManageCallService.SetPayModeCall(bean);
	}
	
	/**
	 * 设置货头的风控金额
	 * 
	 * @param goodsOwnerId
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static void setRiskAmount(long goodsOwnerId, BigDecimal productRiskAmount, BigDecimal tradeRiskAmount)
			throws ClientProtocolException, IOException {

		setShareTypeBean bean=new setShareTypeBean();
		setShareTypeCall call=new setShareTypeCall();
		
		MchInfoVo mchInfo = TradingForDGSQCallService.getMchInfoBySellerId(goodsOwnerId);

		bean.setMchId((int)goodsOwnerId);
		bean.setMchShareType(mchInfo.getmchShareType());
		bean.setPayMode(mchInfo.getPayMode());
		bean.setMchSideBuy(1);
		
		bean.setVipChannel(true);
		
		//风控字段
		bean.setDualMode(mchInfo.getDualMode());//双店模式0：正常模式（默认）1：双店模式
		bean.setProductRiskAmount(productRiskAmount);//商品发布风控金额 0 or null 表示无限制
		bean.setTradeRiskAmount(tradeRiskAmount);//交易发布风控金额 0 or null 表示无限制
		
		call.setData(bean);
		call.callService();
	}
	
	public static void ReduceSqProductStocks(long orderId)
			throws ClientProtocolException, IOException {

		ReduceSqProductStocksReq reduceSqProductStocksReq = new ReduceSqProductStocksReq();
		ReduceSqProductStocksCall reduceSqProductStocksCall = new ReduceSqProductStocksCall();

		reduceSqProductStocksReq.setOrderId(orderId);

		reduceSqProductStocksCall.setData(reduceSqProductStocksReq);
		reduceSqProductStocksCall.callService();

	}
	
	public static void onHpSettled(long paymentId, PaymentPo payment,
			String shengPayRate, int count) throws Exception {
		
		if (count < 6) {
			
			hpSettledReq.setTradingId(paymentId);
			hpSettledReq.setOrderAmount(payment.getRealPaidAmount());
			hpSettledReq.setSettleCurrency(payment.getSettleCurrency());
			hpSettledReq
					.setSettleAmount(payment.getRealForeignAmount() != null ? payment
							.getRealForeignAmount() : payment
							.getForeignAmount());
			
			if (shengPayRate != null) {
				
				hpSettledReq.setSettleFee(payment.getRealPaidAmount().multiply(
						new BigDecimal(shengPayRate)));
			}
			
			hpSettledCall.setData(hpSettledReq);
			hpSettledCall.callService();
			
			if (!"ok".equalsIgnoreCase(hpSettledCall.getReturnData())) {
				
				Thread.sleep(3000 + count * 2000);
				count ++;
				onHpSettled(paymentId, payment, shengPayRate, count);
			}
		} else {
			
			throw new Exception();
		}
	}
	
	/**
	 * 修改身份证信息
	 * @param orderId
	 * @param userId
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void updateSqIdcardInfo(Long orderId, Long userId)
			throws ClientProtocolException, IOException {

		UpdateSqIdcardInfoReq updateSqIdcardInfoReq = new UpdateSqIdcardInfoReq();
		UpdateSqIdcardInfoCall updateSqIdcardInfoCall = new UpdateSqIdcardInfoCall();

		updateSqIdcardInfoReq.setOrderId(orderId);
		updateSqIdcardInfoReq.setUserId(userId);
		updateSqIdcardInfoReq.setIdcardName(TestDataManager.getChineseName());
		updateSqIdcardInfoReq.setIdcardNo(TestDataManager.getCardId(18, 1));

		updateSqIdcardInfoCall.setData(updateSqIdcardInfoReq);
		updateSqIdcardInfoCall.callService();
	}
	
	/**
	 * 是否免税区
	 */
	public static boolean isFreePerimeters(String address) {
		
		if (address.startsWith("香港") || address.startsWith("澳门")
				|| address.startsWith("台湾") || address.startsWith("海外"))
			return true;
		else
			return false;
	}
	
	public static void retryPlaceOrder(PlaceOrderCall placeorderCall, int n) {

		try {

			if (n != 3 && placeorderCall.getCode() == 500) {

				placeorderCall.callService();
				n = n + 1;

				retryPlaceOrder(placeorderCall, n);
			} else if (n == 3)
				throw new Exception("下单失败，终止下单");

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws Exception {

		// TradingForDGSQCallService.getProxyChainInfo("c2285350");

		// TradingForDGSQCallService.getAllParents(500004281);

//		TradingForDGSQCallService.createKRProxychain(500072235, 1, false);
		
//		TradingForDGSQCallService.createNZLProxychain(500173397, 1, false);
		
//		TradingForDGSQCallService.createInheritedProxychain((int) autotest_goodsOwnerId, false);
//		Logger.debug(TradingForDGSQCallService.isInheritedAgent(500221994));
		
		TradingForDGSQCallService.createProxychain((int) 500899225,
				0, false, true);
		
//		TradingForDGSQCallService.getProductDetails(500002490L, "p2717072");

//		Logger.debug(TradingForDGSQCallService.getMchInfoBySellerId(500325125L));
		
//		TradingForDGSQCallService.createWhiteMerchantProxychain(500400836, false);
		
//		TradingForDGSQCallService.setRiskAmount(500583265, new BigDecimal("10000"), new BigDecimal("20000"));
		
//		System.out.println(TradingForDGSQCallService.getAgentRate(500401087, 500403652));
		
//		// 美国供货商
//		AgentProductBean productBean = TradingForDGSQCallService.createSupplierProduct("USA", "CNY", false);
//		
//		Integer mchId = DGSQBaseService.createIndependenceMch("USA");
//		
//		// 创建一个新的渠道商并绑定上级
//		productBean = TradingForDGSQCallService.createChannel(productBean.getSellerId(),
//				productBean.getProductId(), "HKG", (long) mchId);
		
//		productBean = TradingForDGSQCallService.createChannel(productBean.getSellerId(), productBean.getProductId(), "HKG");
//		
//		productBean = TradingForDGSQCallService.createChannel(productBean.getSellerId(), productBean.getProductId(), "JPN");

//		AgentProductBean japanProductBean = TradingForDGSQCallService.createSupplierProduct("JPN", "CNY", false);
//
//		TradingForDGSQCallService.createChannel(japanProductBean.getSellerId(),
//				japanProductBean.getProductId(), productBean.getCurrency(), productBean.getSellerId());

//		Logger.debug(TradingForDGSQCallService.getAmountByCurrency(
//				new BigDecimal("972.00"), "CNY", "JPY"));

//		 AgentProductBean productBean = new AgentProductBean();
//		
//		 productBean.setSellerId(500004881);
//		 productBean.setSellerLoginId("autotest500004881");
//		 productBean.setProductId("p1466630");
//		 productBean.setCatalogList(Lists.newArrayList("c2403528",
//		 "c2403527"));
		//
		// PlaceOrderReq req =
		// TradingForDGSQCallService.buildDGSQStandPlaceOrderReq(0,
		// BigDecimal.ZERO, 20238699, productBean, autotest_goodsOwnerId);
		//
		// TradingCallService.callPlaceOrderService(req);
	}
}
